zoukankan      html  css  js  c++  java
  • Python Web框架(URL/VIEWS/ORM)

    一、路由系统URL
    1、普通URL对应

    url(r'^login/',views.login)

    2、正则匹配

    url(r'^index-(d+).html',views.index)
    url(r'^index-(?P<nid>d+)-(?P<uid>d+).html',views.detail)
    def detail(request,*args,**kwargs):
    pass

    3、name

    url(r'^login/',views.login,name='login_01')
    url(r'^login/(d+)',views.login,name='login_01')
    模板内容:
    {% "login_01" %}
    {% "login_01" 3 %}

    4、include路由分发

    需要导入inclue:
    from django.conf.urls import include, url
    url(r'^cmdb/',include("app01.urls"))

    二、视图VIEWS

    1、获取数据

    request.POST.get()    ##获取单个文本值
    request.POST.getlist()    ##获取多个问本值
    request.FILES.get()    ##获取上传文件内容 <input type='file' name='file_name'>
    obj = request.FILES.get('file_name')
    path = os.path.join('upload', obj.name)
    f = open(path, mode="wb")
    for i in obj.chunks():
    f.write(i)
    f.close()

    2、FBV&CBV

    FBV:function based views
    CBV:class based views

    三、ORM操作
    关系对象映射:Object Relational Mapping,用于实现面向对象编程语言里不同类型系统之间的数据之间的转换。
    所有数据库相关定义在models.py里,然后利用python manage.py makemigrations /python manage.py migrate进行数据库创建

    1、创建类
    a.根据类自动创建数据库表(models.py)

    from django.db import models
    
    # Create your models here.
    class UserInfo(models.Model):
    ##隐含创建id列,主键自增
    username=models.CharField(max_length=32)
    password=models.CharField(max_length=64)

    b.根据类对数据库中的数据进行各种操作(views.py)
    (1)增加数据:

    from cmdb import models
    def orm(request):
    models.UserInfo.objects.create(
    username='root',password='123')
    return HttpResponse('orm')
    或者
    obj=models.UserInfo(username='root',password='123')
    obj.save()

    (2)查询数据:

    已对象形式反回[obj(col1,col2,col3),obj(col1,col2,col3),obj(col1,col2,col3)]

    result=models.UserInfo.objects.all()
    for row in result:
    print(row.id,row.username,row.password)
    result=models.UserInfo.objects.filter(username='root')
    
    a.列表形式
    v1=models.UserInfo.objects.all()
    
    html渲染方式:
    {% for row in v1 %}
    {{row.id}}-{{row.username}}-{{row.code}}
    {% endfor %}

    b.字典形式

    v2=models.UserInfo.objects.all().values('id','username')
    html渲染方式:
    {% for row in v2 %}
    {{row.id}}-{{row.username}}}
    {% endfor %}
    c.元组形式
    v3=models.UserInfo.objects.all().value_list('id','username')
    html渲染方式:
    {% for row in v3 %}
    {{row.0}}-{{row.1}}
    {% endfor %}
    return render(request,'index.html',{'v1':v1,'v2':v2,'v3':v3})

    (3)删除数据

    models.UserInfo.objects.filter(username='root').delete()

    (4)更新数据

    models.UserInfo.objects.filter(username='root').update(password='222')

    (5)一对多操作

    通过外键约束

    b=models.ForeignKey(to="UserInfo",to_field='id')

    (6)多对多操作


    c.常用字段类型

    字符串    models.CharField    字符串字段,不必须设置max_length参数
    models.EmailField
    models.IPAddressField IPV4
    models.GenericIPAddressField IPV4和IPv6
    models.TextField
    数字    models.FloadField
    models.IntegerField
    models.BigIntegerField
    models.Decimal    十进制小数类型,必须指定整数位max_digits和小数位max_places
    models.SmallInteger    
    
    时间    models.DateField    日期类型,对于auto_time=now,每次更新都会更新这个时间;auto_now_add则只是第一次创建添加,之后更新不在改变
    models.DateTimeField
    models.TimeField
    二进制    models.BinaryField    
    布尔    models.BoolenField    布尔类型=tinyint(1),不能为空,Blank=True
    models.NullBoolenField    允许为空的布尔类型
    
    自增    models.AutoField    自增列=int(11) 默认自动创建id自增主键,如果显示设置自增列必须设置其为主键
    其他类型    models.ImageField    图片
    models.FilePathField    文件    
    models.ForeignKey("参考主键表",to_field='主键表列')

    d.常用字段参数

    null:    DB是否可以为空
    default:    默认值
    primary_key:    主键,primary_key=True
    db_column:    列名
    db_index:    索引,db_index=True
    unique:    唯一索引,unique=True
    unique_for_date:    
    unique_for_month:
    unique_for_year:
    choices:    django admin中显示下拉框,避免连表查询
    auto_now:    更新时自动生成
    auto_now_add:    创建时自动生成
    blank:    django admin表示是否为空
    verbose_name:    django admin显示字段中文
    editable:    django admin控制是否被编辑
    error_message:    django admin自定义报错信息
    help_text:    django admin帮助信息
    validators:    django admin自定义错误信息

    2、数据库配置
    settings.py里有数据源配置,默认是sqlite

    DATABASES = {
    'default': {
    'ENGINE': 'django.db.backends.sqlite3',
    'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
    }
    其他支持的数据源配置:
    
    'django.db.backends.postgresql_psycopg2'
    'django.db.backends.mysql'
    'django.db.backends.sqlite3'
    'django.db.backends.oracle'
    
    DATABASES = {
    'default': {
    'ENGINE': 'django.db.backends.postgresql_psycopg2',
    'NAME': 'mydatabase',
    'USER': 'mydatabaseuser',
    'PASSWORD': 'mypassword',
    'HOST': '127.0.0.1',
    'PORT': '5432',
    }
    }

    注意:
    python2里用的MySQLdb模块,而python3里默认没有MySQLdb模块,使用pymysql连接Mysql数据库
    在project同名的__init__.py里需要写入以下代码:
    import pymysql
    pymysql.install_as_MySQLdb()

    3、应用模块导入
    在settings.py中导入相应的应用模块名称

    INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'cmdb',
    )    

    4、生成数据库表结构
    a.生成临时文件,在migrations

    python manage.py makemigrations
    Migrations for 'cmdb':
    0001_initial.py:
    - Create model UserInfo

    b.正式执行生成表结构

    python manage.py migrate
    Operations to perform:
    Synchronize unmigrated apps: messages, staticfiles
    Apply all migrations: cmdb, sessions, auth, admin, contenttypes
    Synchronizing apps without migrations:
    Creating tables...
    Running deferred SQL...
    Installing custom SQL...
    Running migrations:
    Rendering model states... DONE
    Applying cmdb.0001_initial... OK

    创建后的表名为:cmdb_userinfo



    5、登陆示例


    6、Ajax

    $.ajax({
    url:'/host'
    type:"POST"
    data:{'k1':123,'k2':"root"},
    success:function(data){
    
    })
    
    }
    
     
  • 相关阅读:
    zookeeper 简介
    缓存雪崩 缓存穿透
    SpringCloud实战2-Ribbon客户端负载均衡
    SpringCloud实战1-Eureka
    JVM笔记9-Class类文件结构
    JVM笔记8-虚拟机性能监控与故障处理工具
    JVM笔记7-内存分配与回收策略
    SpringAOP-JDK 动态代理和 CGLIB 代理
    MySQL多数据源笔记5-ShardingJDBC实战
    MySQL多数据源笔记4-Mycat中间件实战
  • 原文地址:https://www.cnblogs.com/rangle/p/8134255.html
Copyright © 2011-2022 走看看