mooc在线教育网开发流程总结(五)视图-数据库

1、用户验证:

user = UserProfile.objects.get(Q(username=form.data['username'])| Q(email=form.data['username']))
if user.check_password(form.data['password']):
    login(ruquest,user)
    return HttpResponsePermanentRedirect(reverse('Index'))
else:
    return render(request, 'login.html', {'form': form, 'msg': '密码错误'})

也可以使用authenticate,CustomBackend,login和logout用来管理用户登录时的session和cookies

2、url参数传递给view的方式有:

    1,通过url配置正则表达式

    2,通过get方法获取表单里面的参数

    3,{% url "xxx:xxx" param1 param2%}

{% url "Goods:GoodsClass" goods_class.name %} #html
url('(?P<name>.*)$', GoodsClassView.as_view(), name='GoodsClass'),#urls
def get(self, request, name):#views

3、Mixin混合方式来快速修改页面是否需要登录验证:

@method_decorator(login_required(login_url='Login'), name='dispatch')#可以放在下面,就可去掉name
class LoginRequireMxin(View):
    def dispatch(self, request, *args, **kwargs):
        super(LoginRequireMxin, self).dispatch(request, *args, **kwargs)

4、简单页面flatpage需要在admin里面重新注册了才能显示

5、查询qureset并与SQL语句做对比:

sql的select对应的字段,queryset用.获取

sql的group_by分组功能,queryset是用Goods.objects.values(""),Goods.objects.values_list(""),后面接着annotate聚合起来其他的列

6、聚合函数需要导入包

from django.db.models import Count

sqlite使用

sqlite的读写示例,网上的大多数不是全路径,不同文件调用也会访问不到,实在坑死了 。

import sqlite3


def inquiry_io(ip, disk, cycle):
    with sqlite3.connect('/var/ceph-manager/ceph-manager.db') as conn:
        c = conn.cursor()
        cmd = "select * from IO_TABLE where ip='{0}' and disk='{1}' and cycle = {2} order by time  desc limit 20".format(ip, disk, cycle)
        c.execute(cmd)
        res = []
        for row in c:
            tmp=row[5].split()
            res.append([row[4],tmp[2], tmp[3], tmp[1]])
        res.reverse()
        return res

def insert_io(ip, disk, cycle, _now, data):
    with sqlite3.connect('/var/ceph-manager/ceph-manager.db') as conn:
        c = conn.cursor()
        c.execute('''CREATE TABLE IF NOT EXISTS IO_TABLE
        (ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
        IP TEXT NOT NULL,
        DISK TEXT NOT NULL,
        CYCLE INT NOT NULL,
        TIME TEXT NOT NULL,
        DATA CHAR(50));''')
        cmd= "INSERT INTO IO_TABLE(ID, IP, DISK, CYCLE, TIME, DATA) VALUES (NULL, '{0}','{1}',{2},'{3}','{4}')".format(ip, disk, cycle, _now, data)
        c.execute(cmd)
        conn.commit()
        # c.execute("DROP TABLE IF EXISTS IO_TABLE")

 

展开阅读全文

没有更多推荐了,返回首页