python web django base skill

8065 ワード

Webフレームワークの本質
socket +     

    socket      tonado  node.js
  WSGI  socket  django flask

自分でフレームワークを実現する考え方
wsgiref socket
    
     (views)
jinja2      (templates)       ,            
 db   (models)

Webフレームワークの流れ
  :  wsgi -->      -- views(    ) --- template( html) --- )db  (model)

1      wsgi
    wsgi      env,         conn,        
2        
3    view,     
3 tpl              jinja2
4         ORM(Model)
5     
6       1     conn,    

install django and create a django project
pip install django=1.9.5
django-admin startproject my_site      
cd mysite
python manage.py startapp monitor         APP
python manage.py startapp cmdb            APP1
python manage.py runserver 0.0.0.0:9999

        ,   pycharm       

さあ、djangoを始めましょう
グローバル構成
       ,      
STATICFILES_DIRS = ( os.path.join(BASE_DIV, "statics"), ) js css img    

バックグラウンド管理pyコマンド
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser   #           
python manage.py shell

 settings          

ルーティングシステムurls
           (r"^/index/", vews.index),
         (r"^/index/(\d+)", vews.index),
          (r"^/index/", include("appname.urls")),

templateテンプレート
  
list dict object   .   
li = [1,2,3]
dic = {"k1":"v1", "k2":"v2"}
{{ k1 }}
{{ li.0 }}
{{ dic.k1 }}

    
{% for item in data %}
    {{ item }}
    {{ forloop.counter }}         
    {{ forloop.first }}              
    {{ forloop.last }}                
{% endfor %}

{% if 1 == 1%}
{% else %}
{% endif %}


  
      
    {% block blockname %}
    {% endblock %}

      :
    {% extend "front/xx.html" %}
    
      :     4 block
    title  css content js   html               


  
              
    {% include "front_app/ss.html" %}


    



       --    ,   python  ,    
      :
    filter                if   ,    
    simple_tag             if    


    settings   APP
     APP    templatetags
        py  ,      
        from django import template
        from django.utils.safestring import mark_safe
        from django.template.base import resolve_variable, Node, TemplateSyntaxError

        register = template.Library()  #        
        
        @register.filter
        def plus_10(arg):
            return arg + 10
        
        @register.simple_tag
        def my_simple_time(v1,v2,v3):
            return  v1 + v2 + v3
  
        @register.simple_tag
        def my_input(id,arg):
            result = "" %(id,arg,)
            return mark_safe(result)
            
      :
    {% load xx %}     
    {% k1|f1 %}
    {% my_simple_time 1 2 3%}     ,     
    {% my_input 'id_username' 'hide'%}

単純なデータベース管理
基本的な説明
class  admin
admin.site.register(CLASS)

def __str__():          , model       
  admin       ,          

adminインタフェースのカスタマイズ
      ,   admin.ModelAdmin
class BookAdmin(admin.ModelAdmin):
    list_display = ('name', 'publisher', 'publish_date')
    list_filter = ('publisher', 'publish_date')
    list_editable = ('name', 'publish_date')
    list_per_page = 10 #       
    list_selected_related = ()
    serach_fields = ('name', 'publish__name')  # __ is magic
    
    
    #       
    filter_horizontal = ('authors', )  #       Manytomany
    raw_id_filds = ('publisher', )  #   ForeignKey
    
     xadmin ,    admin,    


  admin action
actions = [f1, ]  #  BookAdmin      ,  f1(bookAdmin, request, querySet)      ,     


      
 model      ,  style
 BookAdmin      list_display = (f1)
    
    
    

データベースモデル
 class
    class User(model)
    modes.CharField(maxlength=32)
    modes.IntegerField()

  settings    INSTALL_APPS

     
python manage.py makemigrations
python manage.py migrate

curd  

models.UserInfo.objects.create(username=“yangli”, password="123456")
models.UserInfo.objects.create(**dict)
obj = models.UserInfo(username="yangli2", password="12345")
obj.save()

models.UserInfo.objects.filter(   ).delete()
models.UserInfo.objects.filter(  ).update(password="123")  #          

models.UserInfo.objects.get(id=1)
models.UserInfo.objects.filter(  ).all()
models.UserInfo.objects.filter(  ).all().values(id,email)     #   
models.UserInfo.objects.filter(  ).all().value_list(id,imail)  # list and tuple
models.UserInfo.objects.filter(  ).first()   last()
models.UserInfo.objects.filter(name="yangli")
models.UserInfo.objects.filter(name__exact="yangli")
models.UserInfo.objects.filter(name__iexact="yangli")
models.UserInfo.objects.filter(name__contains="yangli")
models.UserInfo.objects.filter(name__icontains="yangli")
models.UserInfo.objects.filter(name__startswith="yangli")
models.UserInfo.objects.filter(name__endswith="yangli")
models.UserInfo.objects.filter(name__range=[1, 3]).order_by("-name")  #   
models.UserInfo.objects.all()[0:2]


    
# __ is magic,           
models.Entry.objects.filter(blog__name__contains="    ")
models.Entry.objects.filter(blog__name__icontains="tech")

      
from django.db.models import F
models.Entry.objects.filter(n_comments__gt=F('n_pingbacks') * 2 )
models.Entry.objects.filter(mode_date__gt = F('pub_date') + timedelta(days=3))  #    3         



        :
book -- publisher   one-to-one
book -- authors     many-to-many
new_book = Book(
    title = "learn python to Alex",
    publish_id = publish_id   # class    publish_id,       ,       
    # authors          ,      
)
new_book.save()
new_book.authors.add(1,2,3)
new_book.authors.add(*authors_ids)



         
render(request, "t1.tpl", {"li":users_list})
             
    

   post       ,     settings   csrf



             :
https://docs.djangoproject.com/en/1.10/ref/models/fields/#primary-key

IntegerField()   FloatField()
CharField()  TextField()
DateField()
EmailField()
TimeField()
ImageField()  FieldPathFiled()  #           ,django admin          



Filed option
null=True  #   db
bank=True  #   django admin form
uniq=True
default="default"
primary_key=Truet

auto_now          ,       
auto_now_add      ,      

gender_choices = ((0, "female"),(1,"male"),)
choices=gender_choices

volidators = []
upload_to="upload"  # FileFiled() ImageField()            

データベースの高度な削除
content:

     test.py   django API       
          
    import os
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "projectname.settings")
    import django
    djang.setup()
    
    
    

ルーティングシステム
        
          
    
         
          ?P
           

テンプレートtemplate
レンダーテンプレートjianja 2
         render()      ,    value object,        .        
    
    li = []  dic = {}  user = User(name="yangli", password="123")
    li.1 dic.k1  user.name  user.password
    
        :
    {% for item in objs %}
    {{  item }}
    {% endfor %}
    
    {% if forloop.count0|divisibleby:"2" %}
    {% else %}
    {% endif %}
    
        :
      while  ,  while        ,          
              
               ,render         ,     ,    

テンプレートの継承
      :
            
    {% block name %}
    
    {% endblock %}
    
      :
    {% extend "path" %}  #         
    {% block name %}  #          
    
    {% endblock %}
    
    # include     
    {% include "app01/registor.html" %}
    
        :
            ,            
             
    
    
    
    

フロントエンドfrontend html css js jQuery ajax 6