一、使用django实现之定义分页
1、自定义分页在django模板语言中,通过a标签实现;
2、前段a标签使用<a href="/user_list/?page=1">1</a>,将page的值传送到函数/user_list/中,后端在user_list中通过request.GET.get('page',1)获取当前页;
3、从数据库中获取特定行的数据,使用result = models.UserList.objects.all()[start:end]获取,start和end分别表示开始和结束的行;
3、自定义分页显示到模板语言中的html/css/js的字符串,在django view中,通过python字符串拼接生成;
4、获取分页的起始页,结束页,以及当前页居中等功能,抽象出来,放到一个类中实现;
5、Django默认认为返回给前段的字符串是不安全的(XSS),所有直接返回的html中,会显示为原始的字符串,可以通过在前段使用|safe或者在后端使用后make_safe实现将字符串能够让浏览器进行解析;
6、分页优化需要考虑:让当前页居中,增加上一页和下一页功能;
#-*- coding:utf-8 -*- from django.shortcuts import render from app01 import models from django.utils.safestring import mark_safe # Create your views here. class Pager(object): def __init__(self,current_page): self.current_page = int(current_page) @property def start(self): return (self.current_page -1)*10 @property def end(self): return self.current_page*10 def page_str(self,all_item,base_url): all_page,div = divmod(all_item,10) if div>0: all_page+=1 pager_list = [] if all_page <=11: #分页功能优化,将当前页居中,并且从1开始 start =1 end = all_page else: if self.current_page <=6: start = 1 end = 12 else: start = self.current_page-5 end = self.current_page +6 if self.current_page +6 >all_page: start =all_page -11 end = all_page +1 for i in range(start,end): #让当前页永远居中 if i == self.current_page: temp = '<a style="color:red;font-size:26px;" href="%s%d">%d</a>' %(base_url,i,i) else: temp = '<a href="%s%d">%d</a>' %(base_url,i,i) pager_list.append(temp) #增加上一页和下一页功能 #上一页 if self.current_page >1: pre_page = '<a href="%s%d">上一页</a>' %(base_url,self.current_page-1) else: pre_page = '<a href="javascript:void(0);">上一页</a>' if self.current_page >=all_page: next_page = '<a href="javascript:void(0);">下一页</a>' else: next_page = '<a href="%s%d">下一页</a>' %(base_url,self.current_page+1) pager_list.insert(0,pre_page) pager_list.append(next_page) return mark_safe("".join(pager_list)) #在后端标记html是安全的,前端标记为安全的使用page_str|safe def user_list(request): # for item in range(100,500): # temp = {'username':"name %d" %item,'age':item} # models.UserList.objects.create(**temp) print models.UserList.objects.all().count() #每页显示10条 #向用户显示页数 current_page = request.GET.get('page',1) # print current_page # current_page = int(current_page) # start = (current_page-1)*10 # end = current_page*10 # result = models.UserList.objects.all()[start:end] page_obj = Pager(current_page) result = models.UserList.objects.all()[page_obj.start:page_obj.end] print result.query #对应的sql语句 all_item = models.UserList.objects.all().count() # all_page,div = divmod(all_item,10) # if div>0: # all_page+=1 # # pager_str = "" # for i in range(1,all_page+1): # temp = '<a href="/user_list/?page=%d">%d</a>' %(i,i) # pager_str +=temp pager_str = page_obj.page_str(all_item,"/user_list/?page=") return render(request,'user_list.html',{'result':result,'pager_str':pager_str})
模板语言文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <style> a{ padding: 5px; } </style> </head> <body> <table> {% for line in result %} <tr> <td>{{ line.username }}</td> <td>{{ line.age }}</td> </tr> {% endfor %} </table> <div> {# <a href="/user_list/?page=1">1</a>#} {# <a href="/user_list/?page=2">2</a>#} {# <a href="/user_list/?page=3">3</a>#} {# <a href="/user_list/?page=4">4</a>#} {# {{ pager_str|safe }}#} {{ pager_str }} {# 一般对于返回到网页的字符串,django认为是不安全的,为了防止xss攻击,会将返回的字符串不作解析,以原始字符串的格式返回,使用safe表示我们认为返回的字符串是安全的,可以被浏览器解析#} </div> </body> </html>
二、Bottle
1、只有一个文件,但是至少依赖于两个部件:wsgi和模板引擎;
2、只有在运行时依赖别的模块;
三、Flask
Flask有很多现成的插件可以使用,但是没有自己的模板引擎和wsgi,需要依赖于其他的模本引擎;
四、Tarnado
支持异步非阻塞,见下图
五、自定义Form表单
#!/usr/bin/env python # -*- coding:utf-8 -*- import tornado.ioloop import tornado.web from hashlib import sha1 import os, time import re class MainForm(object): def __init__(self): self.host = "(.*)" self.ip = "^(25[0-5]|2[0-4]d|[0-1]?d?d)(.(25[0-5]|2[0-4]d|[0-1]?d?d)){3}$" self.port = '(d+)' self.phone = '^1[3|4|5|8][0-9]d{8}$' def check_valid(self, request): #request,用户提交的表单 form_dict = self.__dict__ #获取对象的所有字段 #{host:"","ip":""} for key, regular in form_dict.items(): post_value = request.get_argument(key) #获取用户传过来的参数 # 让提交的数据 和 定义的正则表达式进行匹配 ret = re.match(regular, post_value) print key,ret,post_value if not ret: return False return True class MainHandler(tornado.web.RequestHandler): def get(self): self.render('index.html',name='Chales') def post(self, *args, **kwargs): #获取用户form表中的数据,然后验证 obj = MainForm() #验证通过 result = obj.check_valid(self) print result self.write('ok') settings = { 'template_path': 'template', 'static_path': 'static', 'static_url_prefix': '/static/', } application = tornado.web.Application([ (r"/index", MainHandler), ], **settings) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> {{name}} <h1>hello</h1> <form action="/index" method="post"> <p>hostname: <input type="text" name="host" /> </p> <p>ip: <input type="text" name="ip" /> </p> <p>port: <input type="text" name="port" /> </p> <p>phone: <input type="text" name="phone" /> </p> <input type="submit" value="submit" /> </form> </body> </html>
六、如何在自定义的脚本中调用model
#!/usr/bin/env python # _*_ coding:utf-8 _*_ __author__ = "charles" import os os.environ["DJANGO_SETTINGS_MODULE"]="s12crm.settings" import django django.setup() from crm.models import UserProfile entry = UserProfile.objects.last() print entry