欢迎转载,请支持原创,保留原文链接:blog.ilibrary.me

基础

  1. 安装django以后就可以用django-admin
    1. 创建project: django-admin startproject HelloWorld
    2. 创建app: ``
  2. 引入当前目录的内容: from . import views
  3. 安装xmlsec失败,先安装依赖: brew install libxml2 libxmlsec1 pkg-config , https://blog.csdn.net/yuyexiaohan/article/details/107145624
  4. Disallowed Host: Invalid HTTP_HOST header: '127.0.0.1:8000'. You may need to add '127.0.0.1' to ALLOWED_HOSTS
    1. 修改settings.py->’ALLOWED_HOSTS’
  5. django admin app: 'django.contrib.admin'
  6. django admin后台地址: http://localhost:8000/admin
  7. django admin的默认账号,没有。 需要通过命令创建: python manage.py createsuperuser
  8. 给django manager添加命令Django : How can I see a list of urlpatterns?
  9. django admin列出所有的urls(rails routes等价物), 需要装django-extension:
    1. pip install django-extensions
    2. 安装app, settings.py->INSTALLED_APPS, 添加'django_extensions',
  10. Linkedin登录:
    1. 官方django例子, 需要把抛错的app删除,然后配置key&secret, 见下面.
    2. python social auth settings
        # settings.py
        SOCIAL_AUTH_LINKEDIN_OAUTH2_KEY = '77xqioxxxxxxxx'
        SOCIAL_AUTH_LINKEDIN_OAUTH2_SECRET = 'zILxe7jcxxxxxxxx'
        SOCIAL_AUTH_LOGIN_REDIRECT_URL = '/home/'
        SOCIAL_AUTH_LOGIN_URL = '/'
      
      
  11. pip 加速:
      # ~/.pip/pip.conf
        [global]
        index-url = https://mirrors.aliyun.com/pypi/simple/
    
        [install]
        trusted-host=mirrors.aliyun.com
    

    11.

Django shell

Django shell是和rails console类似的东西. Django的manage工具提供了shell命令,帮助我们配置好当前工程的运行环境(如连接好数据库等),以便可以直接在终端中执行测试python语句。

  1. 打开Django shell: python manage.py shell
  2. 导入需要的类型: from exchange_rate.models import ExchangeRate
  3. 查看指定模型的所有记录: ExchangeRate.objects.all()
  4. 查看指定模型的所有记录的数据: ExchangeRate.objects.all().values()
  5. 计数: ExchangeRate.objects.all().count()
  6. 查找指定的记录: ExchangeRate.objects.get(id=1)
  7. 筛选: ExchangeRate.objects.filter(author='xxx')
  8. 创建model object:
    1. er = ExchangeRate(name='xxx');er.save()
    2. ExchangeRate.objects.create(name='xxx')
  9. 删除object: ExchangeRate.objects.filter(id='xxx').delete()

Jupyter notebook

django extensions 支持notebook

  1. 安装依赖: pip install jupyter, pip install ipython
  2. 启动notebook: ./manage.py shell_plus --notebook

    Django admin

    django-admin.py是Django的一个用于管理任务的命令行工具,manage.py是对django-admin.py的简单包装,每个Django Project里面都会包含一个manage.py.

查看有那些命令: python manage.py help

常用子命令:

  1. startproject:创建一个项目(*)
  2. startapp:创建一个app(*)
  3. runserver:运行开发服务器(*)
  4. shell:进入django shell(*)
  5. dbshell:进入django dbshell
  6. check:检查django项目完整性
  7. flush:清空数据库
  8. compilemessages:编译语言文件
  9. makemessages:创建语言文件
  10. makemigrations:生成数据库同步脚本(*)
  11. migrate:同步数据库(*)
  12. showmigrations:查看生成的数据库同步脚本(*)
  13. sqlflush:查看生成清空数据库的脚本(*)
  14. sqlmigrate:查看数据库同步的sql语句(*)
  15. dumpdata:导出数据
  16. loaddata:导入数据
  17. diffsettings:查看你的配置和django默认配置的不同之处

manage.py特有的一些子命令:

  1. createsuperuser:创建超级管理员(*)
  2. changepassword:修改密码(*)
  3. clearsessions:清除session

Admin后台

Django有默认的管理后台。可以自己注册模型,自动生成后台管理页面。

生成后台管理页面的步骤如下:

  1. 生成模型app: ./manage.py startapp communit
  2. 把生成的app注册到apps/settings.py里面去:
    # Application definition
    
    INSTALLED_APPS = [
       'django.contrib.admin',
       'django.contrib.auth',
       #...
       'community'
    ]
    
  3. Community目录下创建admin.py, 填入一下内容:
    from django.contrib import admin
    
    # Register your models here.
    from community.models import Community
    
    class CommunityAdmin(admin.ModelAdmin):
       # Text, Link
       list_display = ('id', 'text', 'link')
    
       # list_display_links = ('id',)
    
    # Register your models here.
    admin.site.register(Community, CommunityAdmin)
    

Model Query

F表达式:

  1. An F() object represents the value of a model field. It makes it possible to refer to model field values and perform database operations using them without actually having to pull them out of the database into Python memory. Instead, Django uses the F() object to generate a SQL expression that describes the required operation at the database level.
  2. F 大概是 field的意思.
  3. 在遇到F表达式的时候会重写python为SQL语句,而不执行python语句
  4. F表达式直接在数据库层面操作
  5. F Expression
  6. 一个F()对象代表一个模型字段的值或注释列。使用它可以直接引用模型字段的值并执行数据库操作而不用把它们导入到python的内存中。

F表达式的应用场景:

  1. 避免竞争条件
  2. 当两个线程同时进行操作,在第一个线程正在操作还未保存的时候,第二个进程进行取值,修改,保存。则第一个操作的值被覆盖丢失。但是由数据库操作的时候则不会出现此种情况。
  3. 用于Queryset中的过滤
  4. F()的实例作为查询中的模型字段的引用。可以用于两个不同字段比较
  5. 支持加减乘除模幂操作,支持位操作

Q表达式,~Q表达式:

  1. A Q() object, like an F object, encapsulates a SQL expression in a Python object that can be used in database-related operations. In general, Q() objects make it possible to define and reuse conditions. This permits the construction of complex database queries using | (OR) and & (AND) operators; in particular, it is not otherwise possible to use OR in QuerySets.
  2. 将SQL表达式封装在可用于数据库相关操作的Python对象中
  3. 支持构造复杂的数据库查询
  4. 支持 OR AND NOT操作

    Celery

Hello world

  1. 异步任务神器 Celery 快速入门教程
  2. 创建tasks.py:
    # -*- coding: utf-8 -*-
    import time
    from celery import Celery
    
    broker = 'redis://127.0.0.1:6379'
    backend = 'redis://127.0.0.1:6379/0'
    
    app = Celery('my_task', broker=broker, backend=backend)
    
    @app.task
    def add(x, y):
       time.sleep(5)     # 模拟耗时操作
       return x + y
    
  3. celery worker -A tasks --loglevel=info
  4. 在python shell里面:
    from tasks import add
    

Djcelery integration

Django Celery source code git

  1. enable djcelery in INSTALLED_APPS: INSTALLED_APPS += ("djcelery", )
  2. add following lines in settings.py:
    import djcelery
    djcelery.setup_loader()
    

    常用命令

  3. python manage.py celery worker
  4. python manage.py celery beat
  5. supervisorctl
    1. tail -f djceler_work
  6. @shared_task 装饰器能让你在没有具体的 Celery 实例时创建任务.

refs

  1. 在 Django 项目中使用 Celery
  2. 异步任务神器 Celery 快速入门教程
  3. DJCelery official doc
  4. Django Celery source code git

    Django extensions

    Django extensions 是django admin的扩展。

  5. show urls: ./manage.py show_urls
  6. shell plus: ./manage.py shell_plus
  7. 运行脚本, django extension自动导入django配置:
    1. 在项目根目录下,创建script文件夹: mkdir scripts && touch scripts/__init__.py
    2. 创建一个脚本文件: touch scripts/delete_all_questions.py
    3. 再次,写脚本。注:代码必须写在 run() 函数下。
        # scripts/delete_all_questions.py
      
        from polls.models import Question
      
        def run():
            # Fetch all questions
            questions = Question.objects.all()
            # Delete questions
            questions.delete()
      
    4. 最后,运行脚本
          python manage.py runscript delete_all_questions
        python manage.py runscript delete_all_questions --traceback # 开启 Debug 模式
      
  8. 启动jupyter notebook: ./manage.py shell_plus --notebook
    1. 需要安装依赖: pip install jupyter && pip install ipython
    2. 不太好用。第二次打开shell_plus book的时候会抛错。

Http

  1. 返回json数据 把数据库记录打包成json格式返回.

     @action(methods=['GET'], detail=False)
     def index(self, request):
         start = request.query_params.get('start_at')
         if not start:
             start = datetime.now() - timedelta(days=30) # by default, start from 30 days before
    
         end = request.query_params.get('end_at')
         if not end or start >= end:
             end = datetime.now()
         print("querying exchange rate from {} to {}".format(start, end))
         exchanges = ExchangeRate.objects.filter(timestamp__range=[start, end]).all()
         serializer_class = ExchangeRateSerializer
         data = serializers.serialize('json', exchanges)
    
         return HttpResponse(data, content_type='application/json')
    
  2. 返回json数据 把hash打包成json格式返回.

         ret = { a: 'bbb'}
         return HttpResponse(json.dumps(ret), content_type='application/json;charset=utf8')
    

Python基础

  1. 多重继承. ClassA.__mro__会打印继承/多重继承的继承链. 函数重名的情况下以这个继承链里第一个找到的符号为准. 重继承,mixin 2.

Python Env

django的很多库对Python版本敏感。建议用conda指定python小版本创建env。

refs

  1. Django/Rails cheat sheet
  2. Django 开发利器 django-extensions
  3. Django Best Practice: Settings file for multiple environments