二、路由系统

路由系统其实就是 url 和 类 的对应关系,这里不同于其他框架,其他很多框架均是 url 对应 函数,Tornado中每个url对应的是一个类。

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3.  
  4. import tornado.ioloop
  5. import tornado.web
  6.  
  7. class MainHandler(tornado.web.RequestHandler):
  8. def get(self):
  9. self.write("Hello, world")
  10.  
  11. class WorkHanlder(tornado.web.RequestHandler):
  12. def get(self,page):
  13.      self.write(page)
  14.  
  15. class StoryHandler(tornado.web.RequestHandler):
  16. def get(self, story_id):
  17. self.write("You requested the story " + story_id)
  18.  
  19. class BuyHandler(tornado.web.RequestHandler):
  20. def get(self):
  21. self.write("buy.wupeiqi.com/index")
  22.  
  23. application = tornado.web.Application([
  24. (r"/index", MainHandler),
  25. (r"/story/([0-9]+)", StoryHandler),
  26.    (r"/work/(?P<page>\d*)",WorkHanlder),
  27. ])
  28.  
  29. application.add_handlers('buy.wupeiqi.com$', [
  30. (r'/index',BuyHandler),
  31. ])
  32.  
  33. if __name__ == "__main__":
  34. application.listen(80)
  35. tornado.ioloop.IOLoop.instance().start()

分页(一页显示五条内容,每页显示11个页码)

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. import tornado.web
  4. import tornado.ioloop
  5. from work.controller import work
  6.  
  7. settings={
  8. "template_path":"tpl",
  9. }
  10.  
  11. application = tornado.web.Application([
  12. (r"/work/(?P<page>\d*)",work.WorkHanlder),
  13. ],**settings)
  14.  
  15. if __name__ == "__main__":
  16. application.listen(8888)
  17. tornado.ioloop.IOLoop.instance().start()

start.py

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. import tornado.web
  4. list_all = ["ssdfsdgsdsgfdf",]
  5. for i in range(100):
  6. list_all.append("123士大夫是的覅是公司的")
  7. class WorkHanlder(tornado.web.RequestHandler):
  8. def get(self,page): #page指的是当前页
  9. list_asd = []
  10. try:
  11. page = int(page) #如果在浏览器上输入的值为整型则正常转
  12. except:
  13. page = 1 #如果输入的值不是int型的,则默认为第一页
  14. start = (page - 1)*5 #内容的开始取值范围
  15. end = page*5 #内容的结束取值范围
  16. list = list_all[start:end] #根据当前页的页码,获取相应页码的内容
  17. all_page ,c = divmod(len(list_all),5) #每页的内容设置为5,超出时下一页显示
  18. if c>0:
  19. all_page+= 1 # 如果余数大于0,说明还需要另一页来显示
  20. if all_page < 11: #设置一页显示11个页码 如果总页数为小于11的话,无论点那一页默认显示全部
  21. s = 1 #页码开始为1
  22. t = all_page #页码结束为总页码
  23. else: #我们设置格式为显示前5后5
  24. if page < 6: #当页码大于11的时候,又分当前页码如果小于6时,显示1-12的页码
  25. s = 1
  26. t = 12
  27. else: #页码大于11且当前页码大于6时又分下面俩种
  28. if all_page > page +5 : #
  29. s = page - 5
  30. t = page + 5 + 1
  31. else:
  32. s = all_page - 11
  33. t = all_page + 1
  34. for p in range(s,t):
  35. if p == page:
  36. temp = "<a href='/work/%s' style='color:red'>%s</a>"%(p,p)
  37. else:
  38. temp = "<a href='/work/%s'>%s</a>"%(p,p)
  39. list_asd.append(temp)
  40. st = "".join(list_asd)
  41. self.render("work.html",list_show = list ,list_page =st,)
  42.  
  43. def post(self, *args, **kwargs):
  44. pass

work.py

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. {% for item in list_show %}
  9. <h3>{{ item }}</h3>
  10. {% end %}
  11.  
  12. {% raw list_page %}
  13. </body>
  14. </html>

work.html

css文件和js文件的引入方式

  1. <link rel="stylesheet" href="{{static_url('chouti.css')}}">
  2. <script src="{{static_url('jquery-1.9.1.min.js')}}"></script>

Tornado中原生支持二级域名的路由,如:

三、模板引擎

Tornao中的模板语言和django中类似,模板引擎将模板文件载入内存,然后将数据嵌入其中,最终获取到一个完整的字符串,再将字符串返回给请求者。

Tornado 的模板支持“控制语句”和“表达语句”,控制语句是使用 {% 和 %} 包起来的 例如 {% if len(items) > 2 %}表达语句是使用 {{ 和 }} 包起来的

,例如 {{ items[0] }}

控制语句和对应的 Python 语句的格式基本完全相同。我们支持 ifforwhile 和 try,这些语句逻辑结束的位置需要用 {% end %} 做标记。还通过 extends 和 block 语句实现了模板继承。这些在 template 模块 的代码文档中有着详细的描述。

注:在使用模板前需要在setting中设置模板路径:"template_path" : "tpl"

1、基本使用

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3.  
  4. import tornado.ioloop
  5. import tornado.web
  6.  
  7. class MainHandler(tornado.web.RequestHandler):
  8. def get(self):
  9. self.render("index.html", list_info = [11,22,33])
  10.  
  11. application = tornado.web.Application([
  12. (r"/index", MainHandler),
  13. ])
  14.  
  15. if __name__ == "__main__":
  16. application.listen(8888)
  17. tornado.ioloop.IOLoop.instance().start()

index

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  5. <title>老男孩</title>
  6. <link href="{{static_url("css/common.css")}}" rel="stylesheet" />
  7. </head>
  8. <body>
  9.  
  10. <div>
  11. <ul>
  12. {% for item in list_info %}
  13. <li>{{item}}</li>
  14. {% end %}
  15. </ul>
  16. </div>
  17.  
  18. <script src="{{static_url("js/jquery-1.8.2.min.js")}}"></script>
  19.  
  20. </body>
  21. </html>

index.html

  1. 在模板中默认提供了一些函数、字段、类以供模板使用:
  2.  
  3. escape: tornado.escape.xhtml_escape 的別名
  4. xhtml_escape: tornado.escape.xhtml_escape 的別名
  5. url_escape: tornado.escape.url_escape 的別名
  6. json_encode: tornado.escape.json_encode 的別名
  7. squeeze: tornado.escape.squeeze 的別名
  8. linkify: tornado.escape.linkify 的別名
  9. datetime: Python datetime 模组
  10. handler: 当前的 RequestHandler 对象
  11. request: handler.request 的別名
  12. current_user: handler.current_user 的別名
  13. locale: handler.locale 的別名
  14. _: handler.locale.translate 的別名
  15. static_url: for handler.static_url 的別名
  16. xsrf_form_html: handler.xsrf_form_html 的別名

2、母版

内容的引入:

在母版的body块中写--------------->{% block body %}{% end %}

在子版中写------------------------{% extends 'layout.html'%} ---------->导入母版

-----------------------------------{% block body %}---------------------->格式

-----------------------------------<h1>work</h1>------------------------>内容

-----------------------------------{% end %}------------------------------>格式

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. <style>
  7. .c1{
  8. height: 40px;
  9. background-color: #2459a2;
  10. }
  11. .c2{
  12. height: 40px;
  13. background-color: black;
  14. }
  15. </style>
  16. </head>
  17. <body>
  18. <div class="c1"></div>
  19. {% block body %}{% end %}
  20. <div class="c2"></div>
  21. </body>
  22. </html>

layout.html

  1. {% extends 'layout.html'%}
  2. {% block body %}
  3. <h1>index</h1>
  4. {% end %}

index.html

  1. {% extends 'layout.html'%}
  2. {% block body %}
  3. <h1>work</h1>
  4. {% end %}

work.html

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. import tornado.web
  4.  
  5. class IndexHanlder(tornado.web.RequestHandler):
  6. def get(self):
  7. self.render("index.html")
  8. def post(self, *args, **kwargs):
  9. pass
  10. class WorkHanlder(tornado.web.RequestHandler):
  11. def get(self):
  12. self.render("work.html")
  13. def post(self, *args, **kwargs):
  14. pas

extend

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. import tornado.web
  4. import tornado.ioloop
  5. from work.controller import work
  6. from work.controller import extend
  7.  
  8. settings={
  9. "template_path":"tpl",
  10. }
  11.  
  12. application = tornado.web.Application([
  13. (r"/work",extend.WorkHanlder),
  14. (r"/index", extend.IndexHanlder),
  15. ],**settings)
  16.  
  17. if __name__ == "__main__":
  18. application.listen(8888)
  19. tornado.ioloop.IOLoop.instance().start()

start.py

css的引入1:

在母版的head块中写--------------->{% block css %}{% end %}

在子版中写--------------------------{% block css %}------------------------------------------------------------------>格式

------------------------------------<link href="{{static_url('s1.css')}}" rel="stylesheet" />----------------------->内容

------------------------------------{% end %}------------------------------------------------------------------------->格式

css的引入2:

在母版的head块中写--------------->{% block css %}{% end %}

在子版中写--------------------------{% block css %}------------------------------------------------------------------>格式

------------------------------------<style>-----------------------------------------------------------------------------------

---------------------------------- .s1{ width: 30px; height: 30px; color: #2459a2; background-color: greenyellow; }

----------------------------------- </style>----------------------------------------------------------------------------------

------------------------------------{% end %}------------------------------------------------------------------------->格式

整体body块、css块、js块母版汇总:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. <link href="{{static_url('s1.css')}}" rel="stylesheet" />
  7. {% block css %}{% end %} <!-- 这里的css和下面的JavaScript大小写都行,只要母版和子版中的一样就行---->
  8. </head>
  9. <body>
  10.  
  11. <div class="c1">11111111</div>
  12. {% block body %}{% end %}
  13. <div class="c2">3333333333</div>
  14.  
  15. <script src="{{static_url('js/jquery-1.8.2.min.js')}}"></script>
  16. {% block javascript %}{% end %}
  17.  
  18. </body>
  19. </html>

母版

  1. {% extends 'layout.html'%}
  2. {% block css %}
  3. <style>
  4. .s1{
  5. width: 30px;
  6. height: 30px;
  7. color: #2459a2;
  8. background-color: greenyellow;
  9. }
  10. </style>
  11. {% end %}
  12. {% block body %}
  13. <div class="s1">123123</div>
  14. <h1>work</h1>
  15. {% end %}
  16.  
  17. <ul>
  18. {% for item in li %}
  19. <li>{{item}}</li>
  20. {% end %}
  21. </ul>
  22.  
  23. {% block javascript %}
  24. <script>
  25. alert("12121212121")
  26. </script>
  27. {% end %}

子版

3、导入

  1. <form action="">
  2. <input type="text">
  3. <input type="text">
  4. </form>

form.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. {% include "form.html" %}
  9. </body>
  10. </html>

index.html

四、cookie

1、基本操作

Cookie是由服务器端生成,发送给User-Agent(一般是浏览器),浏览器会将Cookie的key/value保存到某个目录下的文本文件内,下次请求同一网站时就发送该Cookie给服务器(前提是浏览器设置为启用cookie)

在后台设置cookie:

  1. class IndexHanlder(tornado.web.RequestHandler):
  2. def get(self):
  3. print(self.cookies) #获取http请求中携带的浏览器中的所有cookie
  4. print(self.get_cookie("k1")) # 获取浏览器中的cooki
  5. self.set_cookie("k1","v1") #为浏览器设置cookie

在前端(浏览器上使用JavaScript):

  1. document.cookie #获取浏览器中所有的cookie
  2. document.cookie.split(";") #获取浏览器中具体某一个cookie,需要先分割,再操作
  3. document.cookie = "k1=999" #设置cookie

 由于Cookie保存在浏览器端,所以在浏览器端也可以使用JavaScript来操作Cookie:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. <h1>123</h1>
  9. </body>
  10. <script>
  11. /*设置cookie,指定秒数过期*/
  12. function setCookieBySeconds(name,value,expires){
  13. var current_date = new Date(); //获取当前时间
  14. current_date.setSeconds(current_date.getSeconds() + expires);
  15. document.cookie = name + "= "+ value +";expires=" + current_date.toUTCString();
  16. }
  17. /*设置cookie,指定天数过期*/
  18. function setCookieByDays(name,value,expires){
  19. var current_date = new Date(); //获取当前时间
  20. current_date.setDate(current_date.getDate() + expires);
  21. document.cookie = name + "= "+ value +";expires=" + current_date.toUTCString();
  22. }
  23. </script>
  24. </html>

JavaScript操作Cookie

2、加密cookie(签名)

Cookie 很容易被恶意的客户端伪造。加入你想在 cookie 中保存当前登陆用户的 id 之类的信息,你需要对 cookie 作签名以防止伪造。Tornado 通过 set_secure_cookie 和 get_secure_cookie 方法直接支持了这种功能。 要使用这些方法,你需要在创建应用时提供一个密钥,名字为 cookie_secret。 你可以把它作为一个关键词参数传入应用的设置中:

  1. def _create_signature_v1(secret, *parts):
  2. hash = hmac.new(utf8(secret), digestmod=hashlib.sha1)
  3. for part in parts:
  4. hash.update(utf8(part))
  5. return utf8(hash.hexdigest())
  6.  
  7. # 加密
  8. def _create_signature_v2(secret, s):
  9. hash = hmac.new(utf8(secret), digestmod=hashlib.sha256)
  10. hash.update(utf8(s))
  11. return utf8(hash.hexdigest())
  12.  
  13. def create_signed_value(secret, name, value, version=None, clock=None,
  14. key_version=None):
  15. if version is None:
  16. version = DEFAULT_SIGNED_VALUE_VERSION
  17. if clock is None:
  18. clock = time.time
  19.  
  20. timestamp = utf8(str(int(clock())))
  21. value = base64.b64encode(utf8(value))
  22. if version == 1:
  23. signature = _create_signature_v1(secret, name, value, timestamp)
  24. value = b"|".join([value, timestamp, signature])
  25. return value
  26. elif version == 2:
  27. # The v2 format consists of a version number and a series of
  28. # length-prefixed fields "%d:%s", the last of which is a
  29. # signature, all separated by pipes. All numbers are in
  30. # decimal format with no leading zeros. The signature is an
  31. # HMAC-SHA256 of the whole string up to that point, including
  32. # the final pipe.
  33. #
  34. # The fields are:
  35. # - format version (i.e. 2; no length prefix)
  36. # - key version (integer, default is 0)
  37. # - timestamp (integer seconds since epoch)
  38. # - name (not encoded; assumed to be ~alphanumeric)
  39. # - value (base64-encoded)
  40. # - signature (hex-encoded; no length prefix)
  41. def format_field(s):
  42. return utf8("%d:" % len(s)) + utf8(s)
  43. to_sign = b"|".join([
  44. b"",
  45. format_field(str(key_version or 0)),
  46. format_field(timestamp),
  47. format_field(name),
  48. format_field(value),
  49. b''])
  50.  
  51. if isinstance(secret, dict):
  52. assert key_version is not None, 'Key version must be set when sign key dict is used'
  53. assert version >= 2, 'Version must be at least 2 for key version support'
  54. secret = secret[key_version]
  55.  
  56. signature = _create_signature_v2(secret, to_sign)
  57. return to_sign + signature
  58. else:
  59. raise ValueError("Unsupported version %d" % version)
  60.  
  61. # 解密
  62. def _decode_signed_value_v1(secret, name, value, max_age_days, clock):
  63. parts = utf8(value).split(b"|")
  64. if len(parts) != 3:
  65. return None
  66. signature = _create_signature_v1(secret, name, parts[0], parts[1])
  67. if not _time_independent_equals(parts[2], signature):
  68. gen_log.warning("Invalid cookie signature %r", value)
  69. return None
  70. timestamp = int(parts[1])
  71. if timestamp < clock() - max_age_days * 86400:
  72. gen_log.warning("Expired cookie %r", value)
  73. return None
  74. if timestamp > clock() + 31 * 86400:
  75. # _cookie_signature does not hash a delimiter between the
  76. # parts of the cookie, so an attacker could transfer trailing
  77. # digits from the payload to the timestamp without altering the
  78. # signature. For backwards compatibility, sanity-check timestamp
  79. # here instead of modifying _cookie_signature.
  80. gen_log.warning("Cookie timestamp in future; possible tampering %r",
  81. value)
  82. return None
  83. if parts[1].startswith(b""):
  84. gen_log.warning("Tampered cookie %r", value)
  85. return None
  86. try:
  87. return base64.b64decode(parts[0])
  88. except Exception:
  89. return None
  90.  
  91. def _decode_fields_v2(value):
  92. def _consume_field(s):
  93. length, _, rest = s.partition(b':')
  94. n = int(length)
  95. field_value = rest[:n]
  96. # In python 3, indexing bytes returns small integers; we must
  97. # use a slice to get a byte string as in python 2.
  98. if rest[n:n + 1] != b'|':
  99. raise ValueError("malformed v2 signed value field")
  100. rest = rest[n + 1:]
  101. return field_value, rest
  102.  
  103. rest = value[2:] # remove version number
  104. key_version, rest = _consume_field(rest)
  105. timestamp, rest = _consume_field(rest)
  106. name_field, rest = _consume_field(rest)
  107. value_field, passed_sig = _consume_field(rest)
  108. return int(key_version), timestamp, name_field, value_field, passed_sig
  109.  
  110. def _decode_signed_value_v2(secret, name, value, max_age_days, clock):
  111. try:
  112. key_version, timestamp, name_field, value_field, passed_sig = _decode_fields_v2(value)
  113. except ValueError:
  114. return None
  115. signed_string = value[:-len(passed_sig)]
  116.  
  117. if isinstance(secret, dict):
  118. try:
  119. secret = secret[key_version]
  120. except KeyError:
  121. return None
  122.  
  123. expected_sig = _create_signature_v2(secret, signed_string)
  124. if not _time_independent_equals(passed_sig, expected_sig):
  125. return None
  126. if name_field != utf8(name):
  127. return None
  128. timestamp = int(timestamp)
  129. if timestamp < clock() - max_age_days * 86400:
  130. # The signature has expired.
  131. return None
  132. try:
  133. return base64.b64decode(value_field)
  134. except Exception:
  135. return None
  136.  
  137. def get_signature_key_version(value):
  138. value = utf8(value)
  139. version = _get_version(value)
  140. if version < 2:
  141. return None
  142. try:
  143. key_version, _, _, _, _ = _decode_fields_v2(value)
  144. except ValueError:
  145. return None
  146.  
  147. return key_version

内部算法

签名Cookie的本质是:

写cookie过程:

  • 将值进行base64加密
  • 对除值以外的内容进行签名,哈希算法(无法逆向解析)
  • 拼接 签名 + 加密值

v1 = base64(v1)

k1 =  v1 | 加密串(md5(v1+时间戳+自定义字符串)) | 时间戳

读cookie过程:

  • 读取 签名 + 加密值
  • 对签名进行验证
  • base64解密,获取值内容

五、Session(依赖于cookie)

由于cookie中需要保存客户的很多信息,而且如果信息很多的话,服务端与客户端交互的时候也浪费流量,所以我们需要用很少的一段字符串来保存很多的信息,这就是我们所要引进的session。

cookie 和session 的区别:

1、cookie数据存放在客户的浏览器上,session数据放在服务器上。

2、cookie不是很安全,别人可以分析存放在本地的COOKIE并进行COOKIE欺骗    考虑到安全应当使用session。

3、session会在一定时间内保存在服务器上。当访问增多,会比较占用你服务器的性能    考虑到减轻服务器性能方面,应当使用COOKIE。

4、单个cookie保存的数据不能超过4K,很多浏览器都限制一个站点最多保存20个cookie。

5、所以个人建议:    将登陆信息等重要信息存放为SESSION    其他信息如果需要保留,可以放在COOKIE中

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. import tornado.web
  4. import tornado.ioloop
  5. import hashlib
  6. import time
  7. li = {}
  8. class IndexHanlder(tornado.web.RequestHandler):
  9. def get(self):
  10. obj = hashlib.md5()
  11. obj.update(bytes(str(time.time()),encoding="utf-8"))
  12. random_str = obj.hexdigest()
  13. li[random_str]={}
  14. li[random_str]["k1"]=123
  15. li[random_str]["k2"]=456
  16. li[random_str]["is_login"]=True
  17. self.set_cookie("qqqqqq",random_str)
  18. self.write("成功设置cookie")
  19. def post(self, *args, **kwargs):
  20. pass
  21.  
  22. class ManagerHanlder(tornado.web.RequestHandler):
  23. def get(self):
  24. random_str = self.get_cookie("qqqqqq",None)
  25. current_user_info = li.get(random_str,None)
  26. if not current_user_info:
  27. self.redirect("/index")
  28. else:
  29. if li[random_str]["is_login"]:
  30. self.write("欢迎")
  31. else:
  32. self.redirect("/index")
  33. def post(self, *args, **kwargs):
  34. pass
  35.  
  36. settings={
  37. "template_path":"tpl",
  38. "static_path":"st",
  39. "cookie_secret":""
  40. }
  41.  
  42. class IndeHanlder(tornado.web.RequestHandler):
  43. def get(self):
  44. self.render("1.html")
  45. application = tornado.web.Application([
  46. (r"/index", IndexHanlder),
  47. (r"/manager", ManagerHanlder),
  48. ],**settings)
  49.  
  50. if __name__ == "__main__":
  51. application.listen(8888)
  52. tornado.ioloop.IOLoop.instance().start()

利用session做用户验证

  1. #!/usr/bin/env/python
  2. # -*- coding:utf-8 -*-
  3. import tornado.web
  4.  
  5. container = {}
  6. # container = {
  7. # # "第一个人的随机字符串":{},
  8. # # "第一个人的随机字符串":{'k1': 111, 'parents': '你'},
  9. # }
  10.  
  11. class Session:
  12. def __init__(self, handler):
  13. self.handler = handler
  14. self.random_str = None
  15.  
  16. def __genarate_random_str(self):
  17. import hashlib
  18. import time
  19. obj = hashlib.md5()
  20. obj.update(bytes(str(time.time()), encoding='utf-8'))
  21. random_str = obj.hexdigest()
  22. return random_str
  23.  
  24. def __setitem__(self, key, value):
  25. # 在container中加入随机字符串
  26. # 定义专属于自己的数据
  27. # 在客户端中写入随机字符串
  28. # 判断,请求的用户是否已有随机字符串
  29. if not self.random_str:
  30. random_str = self.handler.get_cookie('__kakaka__')
  31. if not random_str:
  32. random_str = self.__genarate_random_str()
  33. container[random_str] = {}
  34. else:
  35. # 客户端有随机字符串
  36. if random_str in container.keys():
  37. pass
  38. else:
  39. random_str = self.__genarate_random_str()
  40. container[random_str] = {}
  41. self.random_str = random_str
  42.  
  43. container[self.random_str][key] = value
  44. self.handler.set_cookie("__kakaka__", self.random_str)
  45.  
  46. def __getitem__(self, key):
  47. # 获取客户端的随机字符串
  48. # 从container中获取专属于我的数据
  49. # 专属信息【key】
  50. random_str = self.handler.get_cookie("__kakaka__")
  51. if not random_str:
  52. return None
  53. # 客户端有随机字符串
  54. user_info_dict = container.get(random_str,None)
  55. if not user_info_dict:
  56. return None
  57. value = user_info_dict.get(key, None)
  58. return value
  59. class BaseHandler(tornado.web.RequestHandler):
  60. def initialize(self):
  61. self.session = Session(self)
  62. class IndexHandler(BaseHandler):
  63. def get(self):
  64. if self.get_argument('u',None) in ['alex','eric']:
  65. self.session['is_login'] = True
  66. self.session['name'] =self.get_argument('u',None)
  67. print(container)
  68. else:
  69. self.write('请你先登录')
  70. class MangerHandler(BaseHandler):
  71. def get(self):
  72. val = self.session['is_login']
  73. if val:
  74. self.write(self.session['name'])
  75. else:
  76. self.write('登录失败')
  77. class LoginHandler(BaseHandler):
  78. def get(self,*args,**kwargs):
  79. self.render('login.html',status="")
  80. def post(self, *args, **kwargs):
  81. user = self.get_argument('user',None)
  82. pwd = self.get_argument('pwd',None)
  83. code = self.get_argument('code',None)
  84. check_code = self.session['CheckCode']
  85. if code.upper() == check_code.upper():
  86. self.write('验证码正确')
  87. else:
  88. self.render('login.html',status ='验证码错误')
  89. class CheckCodeHandler(BaseHandler):
  90. def get(self,*args,**kwargs):
  91. import io
  92. import check_code
  93. mstream = io.BytesIO()
  94. img, code = check_code.create_validate_code()
  95. img.save(mstream,'GIF')
  96. self.session['CheckCode']=code
  97. self.write(mstream.getvalue())
  98. class CsrfHandler(BaseHandler):
  99. def get(self,*args,**kwargs):
  100. self.render("csrf.html")
  101. def post(self, *args, **kwargs):
  102. self.write("hahahahaah")
  103.  
  104. settings = {
  105. 'template_path':'views',
  106. 'static_path':'static',
  107. "xsrf_cookies":True
  108. }
  109. application = tornado.web.Application([
  110. (r'/index',IndexHandler),
  111. (r'/manger',MangerHandler),
  112. (r'/login',LoginHandler),
  113. (r'/check_code',CheckCodeHandler),
  114. (r'/csrf',CsrfHandler),
  115. ],**settings)
  116.  
  117. if __name__ == "__main__":
  118. application.listen(8888)
  119. tornado.ioloop.IOLoop.instance().start()

session用户验证精简版

六、验证码

验证码原理在于后台自动创建一张带有随机内容的图片,然后将内容通过img标签输出到页面

安装图像处理模块:

  1. pip3 install pillow

步骤:1、首先下载安装pillow图像处理模块------->2、把check_code.py文件和Monaco.ttf文件放在目录下

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. import tornado.ioloop
  4. import tornado.web
  5. import io
  6. import check_code
  7. li = []
  8. class CheckCodeHandler(tornado.web.RequestHandler):
  9. def get(self):
  10. mstream = io.BytesIO()
  11. img, code = check_code.create_validate_code()
  12. li.append(code) #这里可以保存到session中
  13. img.save(mstream, "GIF")
  14. self.write(mstream.getvalue())
  15. print(code)
  16.  
  17. class LoginHandler(tornado.web.RequestHandler):
  18. def get(self):
  19. self.render('login.html',status="")
  20. def post(self, *args, **kwargs):
  21. user = self.get_argument("user",None)
  22. pwd = self.get_argument("pwd",None)
  23. mima = self.get_argument("mima",None)
  24. if user == "alex" and pwd == "" and mima.upper() == li[0].upper(): #不区分大小写
  25. self.write("登录成功")
  26. else:
  27. # self.redirect("/login")
  28. self.render("login.html",status = "验证码错误")
  29.  
  30. settings = {
  31. 'template_path': 'tpl',
  32. 'static_path': 'static',
  33. 'static_url_prefix': '/static/',
  34. 'cookie_secret': 'aiuasdhflashjdfoiuashdfiuh',
  35. }
  36.  
  37. application = tornado.web.Application([
  38. (r"/login", LoginHandler),
  39. (r"/check_code", CheckCodeHandler),
  40. ], **settings)
  41.  
  42. if __name__ == "__main__":
  43. application.listen(8888)
  44. tornado.ioloop.IOLoop.instance().start()

start.py

  1. #!/usr/bin/env python
  2. #coding:utf-8
  3. import random
  4. from PIL import Image, ImageDraw, ImageFont, ImageFilter
  5.  
  6. _letter_cases = "abcdefghjkmnpqrstuvwxy" # 小写字母,去除可能干扰的i,l,o,z
  7. _upper_cases = _letter_cases.upper() # 大写字母
  8. _numbers = ''.join(map(str, range(3, 10))) # 数字
  9. init_chars = ''.join((_letter_cases, _upper_cases, _numbers))
  10.  
  11. def create_validate_code(size=(120, 30),
  12. chars=init_chars,
  13. img_type="GIF",
  14. mode="RGB",
  15. bg_color=(255, 255, 255),
  16. fg_color=(0, 0, 255),
  17. font_size=18,
  18. font_type="Monaco.ttf",
  19. length=4,
  20. draw_lines=True,
  21. n_line=(1, 2),
  22. draw_points=True,
  23. point_chance = 2):
  24. '''
  25. @todo: 生成验证码图片
  26. @param size: 图片的大小,格式(宽,高),默认为(120, 30)
  27. @param chars: 允许的字符集合,格式字符串
  28. @param img_type: 图片保存的格式,默认为GIF,可选的为GIF,JPEG,TIFF,PNG
  29. @param mode: 图片模式,默认为RGB
  30. @param bg_color: 背景颜色,默认为白色
  31. @param fg_color: 前景色,验证码字符颜色,默认为蓝色#0000FF
  32. @param font_size: 验证码字体大小
  33. @param font_type: 验证码字体,默认为 ae_AlArabiya.ttf
  34. @param length: 验证码字符个数
  35. @param draw_lines: 是否划干扰线
  36. @param n_lines: 干扰线的条数范围,格式元组,默认为(1, 2),只有draw_lines为True时有效
  37. @param draw_points: 是否画干扰点
  38. @param point_chance: 干扰点出现的概率,大小范围[0, 100]
  39. @return: [0]: PIL Image实例
  40. @return: [1]: 验证码图片中的字符串
  41. '''
  42.  
  43. width, height = size # 宽, 高
  44. img = Image.new(mode, size, bg_color) # 创建图形
  45. draw = ImageDraw.Draw(img) # 创建画笔
  46.  
  47. def get_chars():
  48. '''生成给定长度的字符串,返回列表格式'''
  49. return random.sample(chars, length)
  50.  
  51. def create_lines():
  52. '''绘制干扰线'''
  53. line_num = random.randint(*n_line) # 干扰线条数
  54.  
  55. for i in range(line_num):
  56. # 起始点
  57. begin = (random.randint(0, size[0]), random.randint(0, size[1]))
  58. #结束点
  59. end = (random.randint(0, size[0]), random.randint(0, size[1]))
  60. draw.line([begin, end], fill=(0, 0, 0))
  61.  
  62. def create_points():
  63. '''绘制干扰点'''
  64. chance = min(100, max(0, int(point_chance))) # 大小限制在[0, 100]
  65.  
  66. for w in range(width):
  67. for h in range(height):
  68. tmp = random.randint(0, 100)
  69. if tmp > 100 - chance:
  70. draw.point((w, h), fill=(0, 0, 0))
  71.  
  72. def create_strs():
  73. '''绘制验证码字符'''
  74. c_chars = get_chars()
  75. strs = ' %s ' % ' '.join(c_chars) # 每个字符前后以空格隔开
  76.  
  77. font = ImageFont.truetype(font_type, font_size)
  78. font_width, font_height = font.getsize(strs)
  79.  
  80. draw.text(((width - font_width) / 3, (height - font_height) / 3),
  81. strs, font=font, fill=fg_color)
  82.  
  83. return ''.join(c_chars)
  84.  
  85. if draw_lines:
  86. create_lines()
  87. if draw_points:
  88. create_points()
  89. strs = create_strs()
  90.  
  91. # 图形扭曲参数
  92. params = [1 - float(random.randint(1, 2)) / 100,
  93. 0,
  94. 0,
  95. 0,
  96. 1 - float(random.randint(1, 10)) / 100,
  97. float(random.randint(1, 2)) / 500,
  98. 0.001,
  99. float(random.randint(1, 2)) / 500
  100. ]
  101. img = img.transform(size, Image.PERSPECTIVE, params) # 创建扭曲
  102.  
  103. img = img.filter(ImageFilter.EDGE_ENHANCE_MORE) # 滤镜,边界加强(阈值更大)
  104.  
  105. return img, strs

check_code.py

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. <form action="/login" method="post">
  9. <p><input name="user" placeholder="用户名" type="text"></p>
  10. <p><input name="pwd" placeholder="密码" type="text"></p>
  11. <p>
  12. <input name="mima" placeholder="验证码" type="text" >
  13. <img src="/check_code" onclick='ChangeCode();' id='imgCode'>
  14. </p>
  15. <input type="submit" value="提交"><span style="color: red">{{status}}</span>
  16. </form>
  17. <script>
  18. function ChangeCode() {
  19. var code = document.getElementById('imgCode');
  20. code.src += '?';
  21. }
  22. </script>
  23. </body>
  24. </html>

login.html

tornado框架之路二的更多相关文章

  1. tornado框架之路三之ajax

    一.ajax 1.传统的Web应用 一个简单操作需要重新加载全局数据 2.AJAX AJAX即“Asynchronous Javascript And XML”(异步JavaScript和XML),是 ...

  2. tornado框架之路一

    Web 服务器 每个页面都以 HTML 的形式传送到你的浏览器中,HTML 是一种浏览器用来描述页面内容和结构的语言.那些负责发送 HTML 到浏览器的应用称之为“Web 服务器”,会让你迷惑的是,这 ...

  3. Tornado框架简介(二)

    --------------------Application-------------------- 1.settings     1.debug=True:,设置tornado是否工作在调试模式, ...

  4. python运维开发(二十二)---JSONP、瀑布流、组合搜索、多级评论、tornado框架简介

    内容目录: JSONP应用 瀑布流布局 组合搜索 多级评论 tornado框架简介 JSONP应用 由于浏览器存在同源策略机制,同源策略阻止从一个源加载的文档或脚本获取或设置另一个源加载的文档的属性. ...

  5. python运维开发(二十三)---tornado框架

    内容目录: 路由系统 模板引擎 cookie 加密cookie 自定义api 自定义session 自定义form表单验证 异步非阻塞 web聊天室实例 路由系统 路由系统其实就是 url 和 类 的 ...

  6. tornado框架&三层架构&MVC&MTV&模板语言&cookie&session

    web框架的本质其实就是socket服务端再加上业务逻辑处理, 比如像是Tornado这样的框架. 有一些框架则只包含业务逻辑处理, 例如Django, bottle, flask这些框架, 它们的使 ...

  7. 用IntelliJ IDEA 开发Spring+SpringMVC+Mybatis框架 分步搭建二:配置MyBatis 并测试(1 构建目录环境和依赖)

    引言:在用IntelliJ IDEA 开发Spring+SpringMVC+Mybatis框架 分步搭建一   的基础上 继续进行项目搭建 该部分的主要目的是测通MyBatis 及Spring-dao ...

  8. 第二百五十九节,Tornado框架-模板语言的三种方式

    Tornado框架-模板语言的三种方式 模板语言就是可以在html页面,接收逻辑处理的self.render()方法传输的变量,将数据渲染到对应的地方 一.接收值渲染 {{...}}接收self.re ...

  9. web框架--tornado框架之模板引擎

    使用Tornado实现一个简陋的任务表功能demo来讲解tornado框架模板引擎 一.demo目录结构 二.具体文件内容 2.1.commons.css .body{ margin: 0; back ...

随机推荐

  1. gridview例子

    直接贴代码 MainActivity.java public class MainActivity extends AppCompatActivity { private GridView _grid ...

  2. 进程间的通讯(IPC)方式

    内存映射 为什么要进行进程间的通讯(IPC (Inter-process communication)) 数据传输:一个进程需要将它的数据发送给另一个进程,发送的数据量在一个字节到几M字节之间共享数据 ...

  3. 【MySQL】binlog缓存的问题和性能

    之前在没有备库的情况下,遇到过more than 'max_binlog_cache_size' bytes of storage 的错误,今天在主备复制的时候又遇到了这个问题 Last_SQL_Er ...

  4. image和字节流之间的相互转换

    //将图片转化为长二进制 public Byte[] SetImgToByte(string imgPath) { FileStream file = new FileStream(imgPath, ...

  5. 值不能为 null 或为空。参数名: linkText

    “/”应用程序中的服务器错误. 值不能为 null 或为空.参数名: linkText 说明: 执行当前 Web 请求期间,出现未经处理的异常.请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的 ...

  6. repo安装

    repo是使用python开发的一个用于多版本管理的工具,可以和git协作,简化git的多版本管理. repo安装: 1.新建~/bin,并将此目录包含在path变量中(如果已存在,且已在path变量 ...

  7. linux内核设计与实现--从内核出发

    linux内核有两种版本:稳定的和处于开发中的. linux通过一种简单的命名机制来区分稳定的和处于开发中的内核,使用3个或者4个“.”分割的数字来代表不同内核版本. 如:2.6.26.1:第一个数字 ...

  8. 在每次request请求时变化session

    session.invalidate();//使得当前的session失效 request.getSession(true).getId();//生成一个新的session 原理: request.g ...

  9. ajaxSubmit中option的参数

    var options = { target: '#output1', // target element(s) to be updated with server response beforeSu ...

  10. java中的final总结

    Java关键字final有最终的,不可改变的含义,它可以修饰非抽象类.非抽象类成员方法和变量. 报错:类"TestFinal"要么是abstract,要么是final的,不能两个都 ...