web框架django第一天练习题

###1. 什么是wsgi?
WSGI(Web Server Gateway Interface)就是一种规范,它定义了使用Python编写的web应用程序与web服务器程序之间的接口格式,
实现web应用程序与web服务器程序间的解耦。


###2. mvc和mtv的区别以及django属于哪一种?
* mvc
    * web应用分为模型(Model),控制器(和Controller),视图(View)三层;他们之间以一种插件似的,松耦合的方式连接在一起。
* mtv
    * Model(模型)、Template(模板)和View(视图),也就是MTV框架。
* MTV模式本质上与MVC模式没有什么差别,也是各组件之间为了保持松耦合关系,只是定义上有些许不同
* django属于mtv


###3. django常见命令
* 安装django
    * pip install django
* 创建django项目,进入创建项目的目录下
    * django-admin startproject mysite
* 创建App
    * python manage.py startapp app01
* 运行django项目
    * python manage.py runserver # 默认8080端口
    * python manage.py runserver 8000  # 指定端口
    * python manage.py runserver 127.0.0.1:8080  # 指定IP和端口
* 创建迁移文件
    * python manage.py makemigrations
* 执行迁移数据库
    * python manage.py migrate
    
    
###4. 如何通过GET和POST向后台传参
* 通过form表单
    * 可以指定method向后台传参的方式,一般为了安全考虑,都是POST方法。
* 通过url
    * 如a标签中的href=路径?k=v的方式,属于GET方法。
* 通过ajax
    * ajax异步提交,可以指定传参的方法,GET和POST都可以。
    

###5. django中如何获取POST和GET传入的参数
* views.py文件中方法的第一个参数request,就可以取到POST和GET传入的参数。
* POST方法:request.POST.get('参数名')
* GET方法:request.GET.get('参数名')


###6. 模板渲染时如何获取列表或字典的元素(根据索引)?
* for循环
    ```html
    {% for user in res %}
    <tr>
        <td>{{ user.id }}</td>
        <td>{{ user.username }}</td>
        <td>{{ user.gender }}</td>
        <td>{{ user.age }}</td>
        <td>{{ user.email }}</td>
        <td>{{ user.phone }}</td>
        <td>{{ user.userType }}</td>
        <td>{{ user.createDateTime }}</td>
        <td><a href="/del_user/?id={{ user.id }}"><span
                class="glyphicon glyphicon-trash"></span></a>
            <span style="padding: 0 10px;"></span>
            <a href="/edit_user/?id={{ user.id }}"><span
                    class="glyphicon glyphicon-edit"></span></a>
        </td>
    </tr>
    {% endfor %}
    ```


###7. 什么是ORM?
* ORM(Object Relational Mapping)对象关系映射,模式是一种为了解决面向对象与关系数据库存在的互不匹配的现象的技术。
* 通过使用描述对象和数据库之间映射的元数据,将程序中的对象自动持久化到关系数据库中。


###8. 创建django程序时需要注意的配置有哪些?
* 配置文件settings.py
    * app配置
    ```python
    INSTALLED_APPS = [
            'django.contrib.admin',
            ...
            'app01',   
            'app01.apps.App01Config'  # 推荐的方式
     ]
    ```
    
    * 模板文件配置,在项目目录下创建templates目录
    ```python
    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [os.path.join(BASE_DIR, templates)], # 模板文件路径
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
            },
        },
    ]
    ```
    
    * 静态文件配置,在项目的目录下创建static目录
    ```python
    STATIC_URL = '/static/'
    STATICFILES_DIRS = [
        os.path.join(BASE_DIR, "static"),  # 静态文件路径
    ]
    ```
    
    * 禁用csrf中间件,方便表单提交测试。
    ```python
    MIDDLEWARE = [
        'django.middleware.security.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        # 'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ]
    ```
    
    * 运行项目报错
    ```python
    Watching for file changes with StatReloader
    Exception in thread django-main-thread:
    Traceback (most recent call last):
      File "G:python3.6lib	hreading.py", line 916, in _bootstrap_inner
        self.run()
      File "G:python3.6lib	hreading.py", line 864, in run
        self._target(*self._args, **self._kwargs)
      File "G:python3.6libsite-packagesdjangoutilsautoreload.py", line 54, in wrapper
        fn(*args, **kwargs)
      File "G:python3.6libsite-packagesdjangocoremanagementcommands
unserver.py", line 109, in inner_run
        autoreload.raise_last_exception()
      File "G:python3.6libsite-packagesdjangoutilsautoreload.py", line 77, in raise_last_exception
        raise _exception[1]
      File "G:python3.6libsite-packagesdjangocoremanagement\__init__.py", line 337, in execute
        autoreload.check_errors(django.setup)()
      File "G:python3.6libsite-packagesdjangoutilsautoreload.py", line 54, in wrapper
        fn(*args, **kwargs)
      File "G:python3.6libsite-packagesdjango\__init__.py", line 24, in setup
        apps.populate(settings.INSTALLED_APPS)
      File "G:python3.6libsite-packagesdjangoapps
egistry.py", line 114, in populate
        app_config.import_models()
      File "G:python3.6libsite-packagesdjangoappsconfig.py", line 211, in import_models
        self.models_module = import_module(models_module_name)
      File "G:python3.6libimportlib\__init__.py", line 126, in import_module
        return _bootstrap._gcd_import(name[level:], package, level)
      File "<frozen importlib._bootstrap>", line 994, in _gcd_import
      File "<frozen importlib._bootstrap>", line 971, in _find_and_load
      File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
      File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
      File "<frozen importlib._bootstrap_external>", line 678, in exec_module
      File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
      File "G:python3.6libsite-packagesdjangocontribauthmodels.py", line 2, in <module>
        from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
      File "G:python3.6libsite-packagesdjangocontribauthase_user.py", line 47, in <module>
        class AbstractBaseUser(models.Model):
      File "G:python3.6libsite-packagesdjangodbmodelsase.py", line 117, in __new__
        new_class.add_to_class('_meta', Options(meta, app_label))
      File "G:python3.6libsite-packagesdjangodbmodelsase.py", line 321, in add_to_class
        value.contribute_to_class(cls, name)
      File "G:python3.6libsite-packagesdjangodbmodelsoptions.py", line 204, in contribute_to_class
        self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
      File "G:python3.6libsite-packagesdjangodb\__init__.py", line 28, in __getattr__
        return getattr(connections[DEFAULT_DB_ALIAS], item)
      File "G:python3.6libsite-packagesdjangodbutils.py", line 201, in __getitem__
        backend = load_backend(db['ENGINE'])
      File "G:python3.6libsite-packagesdjangodbutils.py", line 110, in load_backend
        return import_module('%s.base' % backend_name)
      File "G:python3.6libimportlib\__init__.py", line 126, in import_module
        return _bootstrap._gcd_import(name[level:], package, level)
      File "G:python3.6libsite-packagesdjangodbackendsmysqlase.py", line 36, in <module>
        raise ImproperlyConfigured('mysqlclient 1.3.13 or newer is required; you have %s.' % Database.__version__)
    django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3.
    ```
    * 解决方法
        * G:python3.6Libsite-packagesdjangodbackendsmysqlase.py
            * 找到base.py文件,注释掉 base.py 中如下部分(35/36行)
            ```python
            if version < (1, 3, 13):
                raise ImproperlyConfigured('mysqlclient 1.3.13 or newer is required; you have %s.' % Database.__version__)
            ```
        * G:python3.6Libsite-packagesdjangodbackendsmysqloperations.py
            * 找到operations.py文件(146行),将decode改为encode
            ```python
                def last_executed_query(self, cursor, sql, params):
                    # With MySQLdb, cursor objects have an (undocumented) "_executed"
                    # attribute where the exact query sent to the database is saved.
                    # See MySQLdb/cursors.py in the source distribution.
                    query = getattr(cursor, '_executed', None)
                    if query is not None:
                        query = query.encode(errors='replace')
                    return query
            ```

    * urls.py文件 url路径和函数的对应关系
    ```python
    from app01 import views
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('index/', views.index),
        path('login/', views.login),
        path('baidu/', views.baidu),
    ]
    ```
    
    * 使用MySQL数据库
    ```python
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',  # 引擎
            'NAME': 'day14', # 数据库名
            'HOST': '127.0.0.1', # 数据库IP地址
            'PORT': 3306,  # 数据库端口号
            'USER': 'root', # 数据库用户名
            'PASSWORD': '666'  # 数据库密码
        }
    }
    ```
    
    * mysite项目下的mysite/__init__.py 添加如下内容,告诉Django使用pymysql模块连接MySQL数据库
    ```python
    import pymysql
    pymysql.install_as_MySQLdb()
    ```
    
    * 报错
        ```python
        WARNINGS:
        ?: (mysql.W002) MySQL Strict Mode is not set for database connection 'default'
                HINT: MySQL's Strict Mode fixes many data integrity problems in MySQL, such as data truncation upon insertion, by escalating warnings into errors. It is
        strongly recommended you activate it. See: https://docs.djangoproject.com/en/2.2/ref/databases/#mysql-sql-mode
        ```
        * 在配置中多加一个OPTIONS参数
        ```python
        'OPTIONS': {
            'init_command': "SET sql_mode='STRICT_TRANS_TABLES'"},
        ```

###9. 请写出流程:创建一张表并对其进行增删改查
* 创建数据库
    * create database day14
   
* 创建表mysite/models.py
    ```python
    from django.db import models

    # Create your models here.
    class UserInfo(models.Model):
        username = models.CharField(max_length=32)
        password = models.CharField(max_length=32)
        gender = models.CharField(max_length=6, null=True)
        age = models.IntegerField(default=0)
        email = models.EmailField(null=True)
        phone = models.CharField(max_length=20, null=True)
        userType = models.CharField(max_length=12)
        createDateTime = models.CharField(max_length=32)
    ```
    
* 迁移
    * 创建迁移文件 python manage.py makemigrations
    * 执行迁移数据库 python manage.py migrate
 
* 增
    ```python
    models.UserInfo.objects.create(
            username=username,
            password=md5_pwd,
            gender=gender,
            age=age,
            email=email,
            phone=phone,
            userType=userType,
            createDateTime=createDateTime
        )
    ```

* 删
    ```python
    models.UserInfo.objects.filter(id=user_id).delete()
    ```

* 改
    ```python
    models.UserInfo.objects.filter(id=user_id).update(
                    username=new_name,
                    password=md5_new_pwd,
                    gender=new_gender,
                    age=new_age,
                    email=new_email,
                    phone=new_phone,
                    userType=new_userType
                )
    ```

* 查
    ```python
    models.UserInfo.objects.filter(username=username, password=md5_pwd) # 根据多个条件查
    models.UserInfo.objects.filter(username=usr) # 根据一个条件查
    models.UserInfo.objects.all() # 查所有数据
    models.UserInfo.objects.exclude(id=exclude_id).filter(username=username) # 排除+过滤查询
    ```
    
原文地址:https://www.cnblogs.com/lilyxiaoyy/p/11253428.html