美文网首页
Django 三

Django 三

作者: 吃可爱长大鸭 | 来源:发表于2021-04-18 11:11 被阅读0次

    目录

    1.Django虚拟环境安装
    2.Django路由配置主页与404
    3.Django2.x路由分发
    4.Django伪静态
    5.Djangorequest对象
    6.Django三板斧本质
    7.JsonResponse
    8.DjangoFBV与CBV
    9.Django文件上传
    10.Django settings源码
    

    1.Django虚拟环境安装

    1.通过pip3安装虚拟环境:
        -- pip3 install virtualenv
    2.前往目标文件夹:
        -- cd 目标文件夹  (C:\Virtualenv)
    3.创建纯净虚拟环境:
        -- virtualenv 虚拟环境名 
    了解:创建非纯净环境:
        -- virtualenv-clone 本地环境 虚拟环境名
    4.终端启动虚拟环境:
        -- cd 虚拟环境名\Scripts
        -- activate
    5.进入虚拟环境下的python开发环境
        -- python3
    6.关闭虚拟环境:
        -- deactivate
    7.PyCharm的开发配置
        添加:创建项目 -> Project Interpreter -> Existing interpreter -> Virtualenv Environment | System Interpreter -> 目标路径下的python.exe
        删除:Setting -> Project -> Project Interpreter -> Show All
    

    2.Django路由配置主页与404

    路由层:
    from django.urls import path, re_path
    urlpatterns = [
        # 主页最上方配置
        re_path('^$', root, name="root"),
        re_path('^index/$', index),
        re_path('^home/$', home),
    
        # 其他路由...
    
        # 404配在最下方
        re_path('/$', error)
    ]
    视图层:
    from django.shortcuts import render, redirect, reverse
    # 主页
    def root(request):
        return render(request, 'root.html')
    def index(request):
        return redirect(reverse('root'))
    def home(request):
        return redirect(reverse('root'))
    # 404
    def error(request):
        return render(request, 'error.html')
    

    3.Django2.x路由分发

    1.无名称空间
    主路由:
    path('app01/', include('app01.urls'))
    子路由:
    path('test/', views.test)
    
    2.有名称空间
    主路由:
    path('app01/', include(('app01.urls', 'app01'))),
    子路由:
    path('test/', views.test, name='test')
    模板层:
    {% url 'app01:test' %}
    

    4.Django伪静态

    动态页面:数据内容会发生变化的页面
    静态页面:数据内容不会发生变化的页面
    针对SEO(搜索引擎优化),静态页面更容易被搜索引擎网站收录
    伪静态就是讲动态页面伪装成静态页面,容易被搜索引擎网站收录,从而增加搜索概率,提高流量
    
    路由层:
    url('^index/$', views.index),
    url('^article/(?P<id>(\d+)).html/$', views.article, name='article')
    
    视图函数层:
    def index(request):
        return render(request, 'index.html')
    def article(request, id):
        return render(request, 'article.html', {'id': id})
    
    模板层:
    index.html
    <a href="{% url 'article' 1 %}">第一篇文章</a>
    <a href="{% url 'article' 2 %}">第二篇文章</a>
    <a href="{% url 'article' 3 %}">第三篇文章</a>
    
    article.html
    <h1>第{{ id }}篇文章</h1>
    

    5.Djangorequest对象

    1. method: 请求方式
    2. GET: get请求的参数
    3. POST: post请求的参数(本质是从bdoy中取出来)
    4. body: post提交的数据(不能直接查看)
    5. path: 请求的路径,不带参数
    6. request.get_full_path(): 请求路径,带参数
    7. FILES: 文件数据
    8. encoding: 编码格式
    9. META: 数据大汇总的字典
    

    6.Django三板斧本质

    django视图函数必须要返回一个HttpResponse对象
    
    class HttpResponse(HttpResponseBase):
        """
        An HTTP response class with a string as content.
    
        This content that can be read, appended to or replaced.
        """
        streaming = False
    
        def __init__(self, content=b'', *args, **kwargs):
            super(HttpResponse, self).__init__(*args, **kwargs)
            # Content is a bytestring. See the `content` property methods.
            self.content = content 
            
    def render(request, template_name, context=None, content_type=None, status=None, using=None):
            """
            Returns a HttpResponse whose content is filled with the result of calling
            django.template.loader.render_to_string() with the passed arguments.
            """
            content = loader.render_to_string(template_name, context, request, using=using)
            return HttpResponse(content, content_type, status)
      
    redirect内部是继承了HttpRespone类
    

    7.JsonResponse

    需求:给前端返回json格式数据
    方式1:自己序列化
        res = json.dumps(d,ensure_ascii=False)
        return HttpResponse(res)
    
    方式2:JsonResponse
        from django.http import JsonResponse
        def func2(request):
            d = {'user':'jason好帅','password':123}
            return JsonResponse(d)
      
    ps:额外参数补充
        json_dumps_params={'ensure_ascii':False}  # 看源码
        safe=False  # 看报错信息
     
    # JsonResponse返回的也是HttpResponse对象
    

    8.DjangoFBV与CBV

    FBV:function base views 函数方式完成视图响应
    CBV:class base views 类方式完成视图响应
    
    
    视图层:
    from django.shortcuts import HttpResponse
    from django.views import View
    class CBVView(View):
        def get(self, request):
            return HttpResponse("响应get请求")
        def post(self, request):
            return HttpResponse("响应post请求")
    路由层:
    url('^path/$', views.CBVView.as_views())
    

    9.Django文件上传

    前端:upload.html页面
    1.往自身路径发送post请求,要将第四个中间件注释
    2.multipart/form-data格式允许发送文件
    3.multiple属性表示可以多文件操作
    <form action="" method="post" enctype="multipart/form-data">
        <input type="file" name="files" multiple="multiple">
        <input type="submit" value="上传">
    </form>
    
    def func3(request):
        if request.method == 'POST':
            print(request.POST)
            file_obj = request.FILES.get('myfile')
            print(file_obj.name)  # 获取文件名称
            with open(r'%s'%file_obj.name,'wb') as f:
                for chunks in file_obj.chunks():
                    f.write(chunks)
        return render(request,'func3.html')
    

    10.Django settings源码

    1.django其实有两个配置文件
        一个是暴露给用户可以自定义的配置文件
            项目根目录下的settings.py
        一个是项目默认的配置文件
            当用户不做任何配置的时候自动加载默认配置
    2.配置文件变量名必须是大写
    
    疑问:为什么当用户配置了就使用用户配置的 不配置就是要默认的
    from django.conf import settings
    
    settings = LazySettings()
    
    # manage.py
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings")
    
    ENVIRONMENT_VARIABLE = "DJANGO_SETTINGS_MODULE"
    class LazySettings(LazyObject):
        def _setup(self, name=None):
            # os.environ看成是一个全局大字典      'app.settings'
            settings_module = os.environ.get(ENVIRONMENT_VARIABLE)
            self._wrapped = Settings(settings_module)  # Settings('day05.settings')
     
    class Settings(object):
        def __init__(self, settings_module):  # 'app.settings'
            for setting in dir(global_settings):  # 获取全局配置文件里面所有的变量名
                if setting.isupper():  # 校验是否是纯大写
                    setattr(self, setting, getattr(global_settings, setting))
                    # 给Settings对象添加全局配置文件中所有的配置信息
            
            self.SETTINGS_MODULE = settings_module  # 'app.settings'
            mod = importlib.import_module(self.SETTINGS_MODULE)
            # from app import settings  # 导入暴露给用户的自定义配置文件
            for setting in dir(mod):
                if setting.isupper():
                    setting_value = getattr(mod, setting)
                    setattr(self, setting, setting_value)
    

    相关文章

      网友评论

          本文标题:Django 三

          本文链接:https://www.haomeiwen.com/subject/siwmlltx.html