自定义Web组件
一、Session
1、面向对象基础
面向对象中通过索引的方式访问对象,需要内部实现 __getitem__ 、__delitem__、__setitem__方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
#!/usr/bin/env python # -*- coding:utf-8 -*- class Foo( object ): def __getitem__( self , key): print '__getitem__' ,key def __setitem__( self , key, value): print '__setitem__' ,key,value def __delitem__( self , key): print '__delitem__' ,key obj = Foo() result = obj[ 'k1' ] #obj['k2'] = 'wupeiqi' #del obj['k1'] |
2、Tornado扩展
Tornado框架中,默认执行Handler的get/post等方法之前默认会执行 initialize方法,所以可以通过自定义的方式使得所有请求在处理前执行操作...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
class BaseHandler(tornado.web.RequestHandler): def initialize( self ): self .xxoo = "wupeiqi" class MainHandler(BaseHandler): def get( self ): print ( self .xxoo) self .write( 'index' ) class IndexHandler(BaseHandler): def get( self ): print ( self .xxoo) self .write( 'index' ) |
3、session
session其实就是定义在服务器端用于保存用户回话的容器,其必须依赖cookie才能实现。
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import config
from hashlib import sha1
import os
import time create_session_id = lambda: sha1(bytes('%s%s' % (os.urandom(16), time.time()), encoding='utf-8')).hexdigest() class SessionFactory: @staticmethod
def get_session_obj(handler):
obj = None if config.SESSION_TYPE == "cache":
obj = CacheSession(handler)
elif config.SESSION_TYPE == "memcached":
obj = MemcachedSession(handler)
elif config.SESSION_TYPE == "redis":
obj = RedisSession(handler)
return obj class CacheSession:
session_container = {}
session_id = "__sessionId__" def __init__(self, handler):
self.handler = handler
client_random_str = handler.get_cookie(CacheSession.session_id, None)
if client_random_str and client_random_str in CacheSession.session_container:
self.random_str = client_random_str
else:
self.random_str = create_session_id()
CacheSession.session_container[self.random_str] = {} expires_time = time.time() + config.SESSION_EXPIRES
handler.set_cookie(CacheSession.session_id, self.random_str, expires=expires_time) def __getitem__(self, key):
ret = CacheSession.session_container[self.random_str].get(key, None)
return ret def __setitem__(self, key, value):
CacheSession.session_container[self.random_str][key] = value def __delitem__(self, key):
if key in CacheSession.session_container[self.random_str]:
del CacheSession.session_container[self.random_str][key] class RedisSession:
def __init__(self, handler):
pass class MemcachedSession:
def __init__(self, handler):
pass
自定义session
4、分布式Session
# -*- coding: utf-8 -*-
"""
hash_ring
~~~~~~~~~~~~~~
Implements consistent hashing that can be used when
the number of server nodes can increase or decrease (like in memcached). Consistent hashing is a scheme that provides a hash table functionality
in a way that the adding or removing of one slot
does not significantly change the mapping of keys to slots. More information about consistent hashing can be read in these articles: "Web Caching with Consistent Hashing":
http://www8.org/w8-papers/2a-webserver/caching/paper2.html "Consistent hashing and random trees:
Distributed caching protocols for relieving hot spots on the World Wide Web (1997)":
http://citeseerx.ist.psu.edu/legacymapper?did=38148 Example of usage:: memcache_servers = ['192.168.0.246:11212',
'192.168.0.247:11212',
'192.168.0.249:11212'] ring = HashRing(memcache_servers)
server = ring.get_node('my_key') :copyright: 2008 by Amir Salihefendic.
:license: BSD
""" import math
import sys
from bisect import bisect if sys.version_info >= (2, 5):
import hashlib
md5_constructor = hashlib.md5
else:
import md5
md5_constructor = md5.new class HashRing(object): def __init__(self, nodes=None, weights=None):
"""`nodes` is a list of objects that have a proper __str__ representation.
`weights` is dictionary that sets weights to the nodes. The default
weight is that all nodes are equal.
"""
self.ring = dict()
self._sorted_keys = [] self.nodes = nodes if not weights:
weights = {}
self.weights = weights self._generate_circle() def _generate_circle(self):
"""Generates the circle.
"""
total_weight = 0
for node in self.nodes:
total_weight += self.weights.get(node, 1) for node in self.nodes:
weight = 1 if node in self.weights:
weight = self.weights.get(node) factor = math.floor((40*len(self.nodes)*weight) / total_weight) for j in range(0, int(factor)):
b_key = self._hash_digest( '%s-%s' % (node, j) ) for i in range(0, 3):
key = self._hash_val(b_key, lambda x: x+i*4)
self.ring[key] = node
self._sorted_keys.append(key) self._sorted_keys.sort() def get_node(self, string_key):
"""Given a string key a corresponding node in the hash ring is returned. If the hash ring is empty, `None` is returned.
"""
pos = self.get_node_pos(string_key)
if pos is None:
return None
return self.ring[ self._sorted_keys[pos] ] def get_node_pos(self, string_key):
"""Given a string key a corresponding node in the hash ring is returned
along with it's position in the ring. If the hash ring is empty, (`None`, `None`) is returned.
"""
if not self.ring:
return None key = self.gen_key(string_key) nodes = self._sorted_keys
pos = bisect(nodes, key) if pos == len(nodes):
return 0
else:
return pos def iterate_nodes(self, string_key, distinct=True):
"""Given a string key it returns the nodes as a generator that can hold the key. The generator iterates one time through the ring
starting at the correct position. if `distinct` is set, then the nodes returned will be unique,
i.e. no virtual copies will be returned.
"""
if not self.ring:
yield None, None returned_values = set()
def distinct_filter(value):
if str(value) not in returned_values:
returned_values.add(str(value))
return value pos = self.get_node_pos(string_key)
for key in self._sorted_keys[pos:]:
val = distinct_filter(self.ring[key])
if val:
yield val for i, key in enumerate(self._sorted_keys):
if i < pos:
val = distinct_filter(self.ring[key])
if val:
yield val def gen_key(self, key):
"""Given a string key it returns a long value,
this long value represents a place on the hash ring. md5 is currently used because it mixes well.
"""
b_key = self._hash_digest(key)
return self._hash_val(b_key, lambda x: x) def _hash_val(self, b_key, entry_fn):
return (( b_key[entry_fn(3)] << 24)
|(b_key[entry_fn(2)] << 16)
|(b_key[entry_fn(1)] << 8)
| b_key[entry_fn(0)] ) def _hash_digest(self, key):
m = md5_constructor()
m.update(key.encode('utf-8'))
# return map(ord, m.digest()) # python 2
return list(m.digest()) # pyhton 3
一致性哈希(hash_ring.py)
from hashlib import sha1
import os, time create_session_id = lambda: sha1('%s%s' % (os.urandom(16), time.time())).hexdigest() class Session(object): session_id = "__sessionId__" def __init__(self, request):
session_value = request.get_cookie(Session.session_id)
if not session_value:
self._id = create_session_id()
else:
self._id = session_value
request.set_cookie(Session.session_id, self._id) def __getitem__(self, key):
# 根据 self._id ,在一致性哈西中找到其对应的服务器IP
# 找到相对应的redis服务器,如: r = redis.StrictRedis(host='localhost', port=6379, db=0)
# 使用python redis api 链接
# 获取数据,即:
# return self._redis.hget(self._id, name) def __setitem__(self, key, value):
# 根据 self._id ,在一致性哈西中找到其对应的服务器IP
# 使用python redis api 链接
# 设置session
# self._redis.hset(self._id, name, value) def __delitem__(self, key):
# 根据 self._id 找到相对应的redis服务器
# 使用python redis api 链接
# 删除,即:
return self._redis.hdel(self._id, name)
session
二、表单(form)验证
在Web程序中往往包含大量的表单验证的工作,如:判断输入是否为空,是否符合规则。
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<link href="{{static_url("commons.css")}}" rel="stylesheet" />
</head>
<body>
<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" />
</form>
</body>
</html>
HTML
#!/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):
form_dict = self.__dict__
for key, regular in form_dict.items():
post_value = request.get_argument(key)
# 让提交的数据 和 定义的正则表达式进行匹配
ret = re.match(regular, post_value)
print key,ret,post_value class MainHandler(tornado.web.RequestHandler):
def get(self):
self.render('index.html')
def post(self, *args, **kwargs):
obj = MainForm()
result = obj.check_valid(self)
self.write('ok') settings = {
'template_path': 'template',
'static_path': 'static',
'static_url_prefix': '/static/',
'cookie_secret': 'aiuasdhflashjdfoiuashdfiuh',
'login_url': '/login'
} application = tornado.web.Application([
(r"/index", MainHandler),
], **settings) if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
Python
由于验证规则可以代码重用,所以可以如此定义:
#!/usr/bin/env python
# -*- coding:utf-8 -*- import tornado.ioloop
import tornado.web
import re class Field(object): def __init__(self, error_msg_dict, required):
self.id_valid = False
self.value = None
self.error = None
self.name = None
self.error_msg = error_msg_dict
self.required = required def match(self, name, value):
self.name = name if not self.required:
self.id_valid = True
self.value = value
else:
if not value:
if self.error_msg.get('required', None):
self.error = self.error_msg['required']
else:
self.error = "%s is required" % name
else:
ret = re.match(self.REGULAR, value)
if ret:
self.id_valid = True
self.value = ret.group()
else:
if self.error_msg.get('valid', None):
self.error = self.error_msg['valid']
else:
self.error = "%s is invalid" % name class IPField(Field):
REGULAR = "^(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$" def __init__(self, error_msg_dict=None, required=True): error_msg = {} # {'required': 'IP不能为空', 'valid': 'IP格式错误'}
if error_msg_dict:
error_msg.update(error_msg_dict) super(IPField, self).__init__(error_msg_dict=error_msg, required=required) class IntegerField(Field):
REGULAR = "^\d+$" def __init__(self, error_msg_dict=None, required=True):
error_msg = {'required': '数字不能为空', 'valid': '数字格式错误'}
if error_msg_dict:
error_msg.update(error_msg_dict) super(IntegerField, self).__init__(error_msg_dict=error_msg, required=required) class CheckBoxField(Field): def __init__(self, error_msg_dict=None, required=True):
error_msg = {} # {'required': 'IP不能为空', 'valid': 'IP格式错误'}
if error_msg_dict:
error_msg.update(error_msg_dict) super(CheckBoxField, self).__init__(error_msg_dict=error_msg, required=required) def match(self, name, value):
self.name = name if not self.required:
self.id_valid = True
self.value = value
else:
if not value:
if self.error_msg.get('required', None):
self.error = self.error_msg['required']
else:
self.error = "%s is required" % name
else:
if isinstance(name, list):
self.id_valid = True
self.value = value
else:
if self.error_msg.get('valid', None):
self.error = self.error_msg['valid']
else:
self.error = "%s is invalid" % name class FileField(Field):
REGULAR = "^(\w+\.pdf)|(\w+\.mp3)|(\w+\.py)$" def __init__(self, error_msg_dict=None, required=True):
error_msg = {} # {'required': '数字不能为空', 'valid': '数字格式错误'}
if error_msg_dict:
error_msg.update(error_msg_dict) super(FileField, self).__init__(error_msg_dict=error_msg, required=required) def match(self, name, value):
self.name = name
self.value = []
if not self.required:
self.id_valid = True
self.value = value
else:
if not value:
if self.error_msg.get('required', None):
self.error = self.error_msg['required']
else:
self.error = "%s is required" % name
else:
m = re.compile(self.REGULAR)
if isinstance(value, list):
for file_name in value:
r = m.match(file_name)
if r:
self.value.append(r.group())
self.id_valid = True
else:
self.id_valid = False
if self.error_msg.get('valid', None):
self.error = self.error_msg['valid']
else:
self.error = "%s is invalid" % name
break
else:
if self.error_msg.get('valid', None):
self.error = self.error_msg['valid']
else:
self.error = "%s is invalid" % name def save(self, request, upload_path=""): file_metas = request.files[self.name]
for meta in file_metas:
file_name = meta['filename']
with open(file_name,'wb') as up:
up.write(meta['body']) class Form(object): def __init__(self):
self.value_dict = {}
self.error_dict = {}
self.valid_status = True def validate(self, request, depth=10, pre_key=""): self.initialize()
self.__valid(self, request, depth, pre_key) def initialize(self):
pass def __valid(self, form_obj, request, depth, pre_key):
"""
验证用户表单请求的数据
:param form_obj: Form对象(Form派生类的对象)
:param request: Http请求上下文(用于从请求中获取用户提交的值)
:param depth: 对Form内容的深度的支持
:param pre_key: Html中name属性值的前缀(多层Form时,内部递归时设置,无需理会)
:return: 是否验证通过,True:验证成功;False:验证失败
""" depth -= 1
if depth < 0:
return None
form_field_dict = form_obj.__dict__
for key, field_obj in form_field_dict.items():
print key,field_obj
if isinstance(field_obj, Form) or isinstance(field_obj, Field):
if isinstance(field_obj, Form):
# 获取以key开头的所有的值,以参数的形式传至
self.__valid(field_obj, request, depth, key)
continue
if pre_key:
key = "%s.%s" % (pre_key, key) if isinstance(field_obj, CheckBoxField):
post_value = request.get_arguments(key, None)
elif isinstance(field_obj, FileField):
post_value = []
file_list = request.request.files.get(key, None)
for file_item in file_list:
post_value.append(file_item['filename'])
else:
post_value = request.get_argument(key, None) print post_value
# 让提交的数据 和 定义的正则表达式进行匹配
field_obj.match(key, post_value)
if field_obj.id_valid:
self.value_dict[key] = field_obj.value
else:
self.error_dict[key] = field_obj.error
self.valid_status = False class ListForm(object):
def __init__(self, form_type):
self.form_type = form_type
self.valid_status = True
self.value_dict = {}
self.error_dict = {} def validate(self, request):
name_list = request.request.arguments.keys() + request.request.files.keys()
index = 0
flag = False
while True:
pre_key = "[%d]" % index
for name in name_list:
if name.startswith(pre_key):
flag = True
break
if flag:
form_obj = self.form_type()
form_obj.validate(request, depth=10, pre_key="[%d]" % index)
if form_obj.valid_status:
self.value_dict[index] = form_obj.value_dict
else:
self.error_dict[index] = form_obj.error_dict
self.valid_status = False
else:
break index += 1
flag = False class MainForm(Form): def __init__(self):
# self.ip = IPField(required=True)
# self.port = IntegerField(required=True)
# self.new_ip = IPField(required=True)
# self.second = SecondForm()
self.fff = FileField(required=True)
super(MainForm, self).__init__() #
# class SecondForm(Form):
#
# def __init__(self):
# self.ip = IPField(required=True)
# self.new_ip = IPField(required=True)
#
# super(SecondForm, self).__init__() class MainHandler(tornado.web.RequestHandler):
def get(self):
self.render('index.html')
def post(self, *args, **kwargs):
# for i in dir(self.request):
# print i
# print self.request.arguments
# print self.request.files
# print self.request.query
# name_list = self.request.arguments.keys() + self.request.files.keys()
# print name_list # list_form = ListForm(MainForm)
# list_form.validate(self)
#
# print list_form.valid_status
# print list_form.value_dict
# print list_form.error_dict # obj = MainForm()
# obj.validate(self)
#
# print "验证结果:", obj.valid_status
# print "符合验证结果:", obj.value_dict
# print "错误信息:"
# for key, item in obj.error_dict.items():
# print key,item
# print self.get_arguments('favor'),type(self.get_arguments('favor'))
# print self.get_argument('favor'),type(self.get_argument('favor'))
# print type(self.get_argument('fff')),self.get_argument('fff')
# print self.request.files
# obj = MainForm()
# obj.validate(self)
# print obj.valid_status
# print obj.value_dict
# print obj.error_dict
# print self.request,type(self.request)
# obj.fff.save(self.request)
# from tornado.httputil import HTTPServerRequest
# name_list = self.request.arguments.keys() + self.request.files.keys()
# print name_list
# print self.request.files,type(self.request.files)
# print len(self.request.files.get('fff')) # obj = MainForm()
# obj.validate(self)
# print obj.valid_status
# print obj.value_dict
# print obj.error_dict
# obj.fff.save(self.request)
self.write('ok') settings = {
'template_path': 'template',
'static_path': 'static',
'static_url_prefix': '/static/',
'cookie_secret': 'aiuasdhflashjdfoiuashdfiuh',
'login_url': '/login'
} application = tornado.web.Application([
(r"/index", MainHandler),
], **settings) if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
自定义Web组件的更多相关文章
- AmazeUI(妹子UI)中CSS组件、JS插件、Web组件的区别
AmazeUI(妹子UI)是非常优秀的国产前端UI,现在来介绍一下AmazeUI中CSS组件.JS插件与Web组件的区别. CSS组件顾名思义就是仅使用CSS渲染而成的组件,而JS插件也很容易理解,就 ...
- angular custom Element 自定义web component
angular 自定义web组件: 首先创建一个名为myCustom的组件. 引入app.module: ... import {customComponent} from ' ./myCustom. ...
- amazeui中css组件、js组件、web组件的区别
amazeui中css组件.js组件.web组件的区别 一.总结 一句话总结: 1.可直接像调用js插件那样调用:在AmazeUI(妹子UI)中,Web组件可以不编写模板而直接使用,若如此,则与JS插 ...
- 使用外部web组件-----easyUI、jQueryUI、Bootstrap、js正则表达式
1.使用外部web组件,以Bootstrap为例 <head> <link rel='stylesheet' href='bootstrap-3.3.0-dist/dist/css ...
- 使用shadow dom封装web组件
什么是shadow dom? 首先我们先来看看它长什么样子.在HTML5中,我们只用写如下简单的两行代码,就可以通过 <video> 标签来创建一个浏览器自带的视频播放器控件. <v ...
- Mozilla Brick:一个Web组件Polyfill库
Web组件是一个W3C规范,它旨在使Web开发人员能够定义具有非常丰富的视觉效果和高可交互性且易于组合的小组件.Brick库提供了新的自定义HTML标签,从而抽象了用户常用接口模式.在浏览器本身支持类 ...
- [C# 网络编程系列]专题四:自定义Web浏览器
转自:http://www.cnblogs.com/zhili/archive/2012/08/24/WebBrowser.html 前言: 前一个专题介绍了自定义的Web服务器,然而向Web服务器发 ...
- [阿当视频]WEB组件学习笔记
— 视频看完了,自定义事件还不懂,等完全懂了再更新并完成整篇案例 1. JS分层和组件的种类浏览器底层包括HTML CSS JS(DOM/BOM/Style/Canvas 2D/WebGl/SVG) ...
- web组件开发入门
本文是学习慕课网阿当大话西游之WEB组件后的一个总结. 组件的分类 1 框架组件:依赖于某种框架的组件 2 定制组件:根据公司业务定制的组件 3 独立组件:不依赖框架的组件 定义和加载组件 解决css ...
随机推荐
- Beta 冲刺 六
团队成员 051601135 岳冠宇 031602629 刘意晗 031602248 郑智文 031602330 苏芳锃 031602234 王淇 照片 项目进展 岳冠宇 昨天的困难 ActionBa ...
- PAT 甲级 1029 Median
https://pintia.cn/problem-sets/994805342720868352/problems/994805466364755968 Given an increasing se ...
- Redis常见面题
介绍:Redis 是一个开源的使用 ANSI C 语言编写.遵守 BSD 协议.支持网络.可基于内存亦可持久化的日志型.Key-Value 数据库,并提供多种语言的 API的非关系型数据库. 传统数据 ...
- Windows 创建计划任务 实现自动同步文件.
0 感觉自己还是缺乏让计算机去工作的思维, 缺少编程和算法的想法与实践做法. 0x1 打开计划任务 方法: 运行-> 输入 control -> 大图标->管理工具 打开任务计划程序 ...
- JS频率控制函数
/** * 频率控制 返回函数连续调用时,fn 执行频率限定为每多少时间执行一次 * @param {Function} fn 需要调用的函数 * @param {Number} delay 延迟时间 ...
- Codeforces 859D - Third Month Insanity
题意 有 \(2^n\) 个人要进行比赛,每次 \(2i\) 与 \(2i+1\) 号人进行比赛(\(i\in [0,2^{n-1})\) ).这一轮中赢的人进入下一轮.下一轮比赛的时候把进入这一轮的 ...
- Strategic Game HDU - 1054(最小顶点覆盖)
最小顶点覆盖:用最少的点,让每条边都至少和其中一个点关联: ...以为自己很聪明..用边连边...最后还是点连点 哎.... hc 写的 匈牙利足够///// #include <iostr ...
- bzoj 3531 [Sdoi2014]旅行 (树剖+线段树 动态开点)
3531: [Sdoi2014]旅行 Time Limit: 40 Sec Memory Limit: 512 MBSubmit: 2984 Solved: 1312[Submit][Status ...
- ubuntu中报错:无法分配内存 (errno=12)
今天碰到一个大坑,差点要了老命! 之前装了ubuntu双系统,后来崩溃,想在就想装VMware虚拟机,再装ubuntu,一切进展顺利,直到在虚拟机的ubuntu中安装IDEA时出现了问题. 安装过程并 ...
- 滥用基于资源约束委派来攻击Active Directory
0x00 前言 早在2018年3月前,我就开始了一场毫无意义的争论,以证明TrustedToAuthForDelegation属性是无意义的,并且可以在没有该属性的情况下实现“协议转换”.我相信,只要 ...