zoukankan      html  css  js  c++  java
  • Pytho之Django

    Django工程目录讲解:

    manage.py脚本:用于管理Django站点
    
    settings.py: 包含项目的所有配置参数
    
    urls.py: URL根配置
    
    wsgi.py: 内置runserver命令的WSGI应用配置
    
    __init__.py: 用来告诉python,当前目录是python模块
     
    model.py :实体对象的创建
    
    views.py : 书写业务逻辑
    
    templates目录 :存放html模板

    1、安装Django

    pip install Django

    2、pycharm创建工程

    3、安装mysql_python

    pip install mysql_python

    4、在settings文件中添加

    DATABASES = {
            'default': {
                'ENGINE': 'django.db.backends.mysql',   # 数据库引擎
                'NAME': 'mydb',         # 你要存储数据的库名,事先要创建之
                'USER': 'root',         # 数据库用户名
                'PASSWORD': 'yang156122',     # 密码
                'HOST': 'localhost',    # 主机
                'PORT': '3306',         # 数据库使用的端口
            }
        }

    5、在settings.py同级的__init__.py文件中添加

    import pymysql
        pymysql.install_as_MySQLdb()
        #前面两行是重要的,后面这些是测试用的,这里打印出mysql的版本,显示在程序运行界面上
    
        db = pymysql.connect(host='localhost', user='root', password='yang156122', db='mydb')
    
        cursor = db.cursor()
    
        cursor.execute('SELECT VERSION()')
        data = cursor.fetchone()
        print('DATABASE VERSION IS: %s' % data)
        db.close()

    6、在models.py中创建实体对象

    from django.db import models
        #实体对象
        class Web(models.Model):
            id = models.AutoField(primary_key=True) #主键
            name = models.CharField(max_length=20)
            age = models.IntegerField()  #注意,int类型不需要指定长度
            score = models.CharField(max_length=20)

    7、根据6中的实体对象创建数据库表

    python manage.py makemigrations
    python manage.py migrate 

    8、在views文件中书写逻辑

    from Hello.models import Web
        def sayHello(request):
            s = 'Hello World!'
            current_time = datetime.datetime.now()
            html = '<html><head></head><body><h1> %s </h1><p> %s </p></body></html>' % (s, current_time)
            return HttpResponse(html)

    9、在url.py中添加8中的函数路径映射

        urlpatterns = [
        path('admin/', admin.site.urls),
        url(r'^hello/', viewStudent.sayHello), 
        ]

    注意:在post请求中以json作为入参,请将settings.py文件中的MIDDLEWARE列表中的('django.middleware.csrf.CsrfViewMiddleware',注释掉)

    Demo地址:https://github.com/812406210/Django.git

  • 相关阅读:
    进程与线程
    the art of seo(chapter seven)
    the art of seo(chapter six)
    the art of seo(chapter five)
    the art of seo(chapter four)
    the art of seo(chapter three)
    the art of seo(chapter two)
    the art of seo(chapter one)
    Sentinel Cluster流程分析
    Sentinel Core流程分析
  • 原文地址:https://www.cnblogs.com/ywjfx/p/11761937.html
Copyright © 2011-2022 走看看