欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python的Tornado框架實現(xiàn)異步非阻塞訪問數(shù)據(jù)庫的示例

 更新時間:2016年06月30日 17:55:55   作者:cangmean  
Tornado框架的異步非阻塞特性是其最大的亮點,這里我們將立足于基礎來介紹一種簡單的Python的Tornado框架實現(xiàn)異步非阻塞訪問數(shù)據(jù)庫的示例:

tornado即是一個http非阻塞服務器, 就要用起來, 我們將用到tornado框架 ,mongodb數(shù)據(jù)庫 以及motor(mongodb的異步驅動).來簡單實現(xiàn)tornado的非阻塞功能.

其他環(huán)境支持的下載與安裝

1.安裝mongodb

$ sudo apt-get install update
$ sudo apt-get install mongodb

2.安裝motor

$ pip install motor

非阻塞

# conf.py

import os
import motor
from handlers import index, auth

BASE_DIR = os.path.join(__file__)

handlers = [
  (r'^/$', index.IndexHandler),
  (r'^/auth/register$', auth.RegisterHandler),
  (r'^/auth/login$', auth.LoginHandler),
]

settings = dict(
  debug = True,
  template_path = os.path.join(BASE_DIR, 'templates'),
  static_path = os.path.join(BASE_DIR, 'static'),
)

client = motor.MotorClient("127.0.0.1")
db = client.meet

首先在配置文件中連接數(shù)據(jù)庫, client.db_name中 db_name就是數(shù)據(jù)庫的名稱

 # handlers/__init__.py
class BaseHandler(tornado.web.RequestHandler, TemplateRendering):
  def initialite(self):
    ...

  @property
  def db(self):
    return self.application.db

添加db()并使用property裝飾,像屬性一樣訪問數(shù)據(jù)庫.

# auth.py

import os 
import time 
import tornado.web
from tornado import gen
from . import BaseHandler

class RegisterHandler(BaseHandler):
  def get(self):
    self.render_html('register.html')

  @tornado.web.asynchronous
  @gen.coroutine
  def post(self):
    username = self.get_argument('username', None)
    email = self.get_argument('email', None)
    password = self.get_argument('password', None)

    data = {
      'username': username,
      'email': email,
      'password': password,
      'timestamp': time.time() * 1000,
    }

    if username and email:
      yield self.db.user.insert(data)
    self.redirect('/')

class LoginHandler(BaseHandler):
  
  @tornado.web.asynchronous
  @gen.coroutine
  def get(self):
    username = self.get_argument('useranme')
    user = yield self.db.user.find_one({'username': username})
    self.render_html('login.html', user=user)


@gen.coroutine裝飾使函數(shù)非阻塞, 返回一個生成器, 而不用在使用回調函數(shù). motor也通過yield 實現(xiàn)異步(不然還得返回一個回調函數(shù)). 其實這個例子反映不了阻塞問題關鍵是時間太短.
我們修改一下代碼

# 之前
yield self.db.user.insert(data)

# 之后
yield tornado.gen.Task(tornado.ioloop.IOLoop.instance().add_timeout, time.time() + 10)

這里通過tornado.ioloop.IOLoop.instance().add_timeout阻塞應用, 這是time.sleep的非阻塞實現(xiàn), 如果這里使用time.sleep因為是tornado是單線程會阻塞整個應用所以別的handler也無法訪問.
可以看到我在注冊頁面注冊后,在阻塞期間點擊/auth/login直接就訪問了login頁完成非阻塞.

異步下的redirect問題
在使用tornado的時候常常遇到一些問題, 特將遇到的問題和解決的方法寫出來(這里的感謝一下幫我解答疑惑的pythonista們)

1.問題

我想要實現(xiàn)一個注冊用戶功能, web框架使用tornado數(shù)據(jù)庫使用mongodb但在注冊時出現(xiàn)Exception redirect的錯誤. 現(xiàn)貼下代碼:

class Register(BaseHandler):
  def get(self):
    self.render_html('register.html')

  @tornado.web.aynchronous
  @gen.coroutine
  def post(self):
    username = self.get_argument('username')
    email = self.get_argument('email')
    password = self.get_argument('password')
    captcha = self.get_argument('captcha')

    _verify_username = yield self.db.user.find_one({'username': username})
    if _verify_username:
      self.flash(u'用戶名已存在', 'error')
      self.redirect('/auth/register')

    _verify_email = yield self.db.user.find_one({'email': email})
    if _verify_email:
      self.flash(u'郵箱已注冊', 'error')
      self.redirect('/auth/register')

    if captcha and captcha == self.get_secure_cookie('captcha').replace(' ',''):
      self.flash(u'驗證碼輸入正確', 'info')
    else:
      self.flash(u'驗證碼輸入錯誤', 'error')
      self.redirect('/auth/register')

    password = haslib.md5(password + self.settings['site']).hexdigest()

    profile = {'headimg': '', 'site': '', 'job': '', 'signature':'',
          'github': '', 'description': ''}
    user_profile = yield self.db.profile.insert(profile)
    user = {'username': username, 'email': email, 'password': password,
        'timestamp': time.time(), 'profile_id': str(user_profile)}

    yield self.db.user.insert(user)
    self.set_secure_cookie('user', username)
    self.redirect('/')

本想如果用戶驗證碼輸入出錯就跳轉到注冊頁面, 但問題是驗證碼出錯也會繼續(xù)執(zhí)行一下代碼. 雖然在self.redirect后加上self.finish會終止代碼,但是因為self.redirect 函數(shù)內已有self.finish所以出現(xiàn)了兩次報出異常終止的代碼.
因為以上原因代碼不會被終結, 驗證碼出錯用戶還是會注冊.

2.解決方案

return self.redirect('/auth/register')


self.redirect('/auth/register')
return

(1)segmentdefault中熱心用戶rsj217給出的答案
self.finish 會關掉請求, 因為@tornado.web.aynchronous告訴tornado會一直等待請求(長鏈接). self.redirect等于設置了response的headers的location屬性.

(2)segmentdefault中熱心用戶依云給出的答案
self.finish當然不會跳出函數(shù), 不然請求結束之后還想做些事情怎么辦呢.

3.總結

因為錯把self.finish當做跳出函數(shù)出現(xiàn)了以上的問題

  • self.redirect會在request.headers 里設置location用于跳轉
  • self.finish會關掉請求, 但不會跳出函數(shù)

相關文章

  • 深入理解Python中的super()方法

    深入理解Python中的super()方法

    super 是用來解決多重繼承問題的,直接用類名調用父類方法在使用單繼承的時候沒問題,但是如果使用多繼承,會涉及到查找順序(MRO)、重復調用(鉆石繼承)等種種問題。這篇文章主要給大家介紹了關于Python中super()方法的相關資料,需要的朋友可以參考下。
    2017-11-11
  • Python?中OS?module的使用詳解

    Python?中OS?module的使用詳解

    這篇文章主要介紹了Python?中OS?module的使用詳解,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-03-03
  • Python如何生成樹形圖案

    Python如何生成樹形圖案

    這篇文章主要為大家詳細介紹了Python如何生成樹形圖案,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-01-01
  • Python變量作用范圍實例分析

    Python變量作用范圍實例分析

    這篇文章主要介紹了Python變量作用范圍,實例分析了Python中變量的定義與相關作用域,是Python學習中非常重要的基本技巧,需要的朋友可以參考下
    2015-07-07
  • python?實現(xiàn)?pymysql?數(shù)據(jù)庫操作方法

    python?實現(xiàn)?pymysql?數(shù)據(jù)庫操作方法

    這篇文章主要介紹了python實現(xiàn)pymysql數(shù)據(jù)庫操作方法,文章基于python的相關內容展開對?pymysql?數(shù)據(jù)庫操作方法的詳細介紹,具有一定的參考價值,需要的小伙伴可以參考一下
    2022-04-04
  • Python多進程同步簡單實現(xiàn)代碼

    Python多進程同步簡單實現(xiàn)代碼

    這篇文章主要介紹了Python多進程同步簡單實現(xiàn)代碼,涉及Python基于Process與Lock模塊運行進程與鎖機制實現(xiàn)多進程同步的相關技巧,需要的朋友可以參考下
    2016-04-04
  • python使用wxpy實現(xiàn)微信消息防撤回腳本

    python使用wxpy實現(xiàn)微信消息防撤回腳本

    這篇文章主要為大家詳細介紹了python使用wxpy實現(xiàn)微信消息防撤回腳本,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-04-04
  • python實現(xiàn)可將字符轉換成大寫的tcp服務器實例

    python實現(xiàn)可將字符轉換成大寫的tcp服務器實例

    這篇文章主要介紹了python實現(xiàn)可將字符轉換成大寫的tcp服務器,通過tcp服務器端實現(xiàn)針對字符的轉換與返回功能,具有一定參考借鑒價值,需要的朋友可以參考下
    2015-04-04
  • Python計算素數(shù)個數(shù)的兩種方法

    Python計算素數(shù)個數(shù)的兩種方法

    本文主要介紹了Python計算素數(shù)個數(shù)的兩種方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2023-05-05
  • Django單元測試中Fixtures的使用方法

    Django單元測試中Fixtures的使用方法

    這篇文章主要介紹了Django單元測試中Fixtures用法詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-02-02

最新評論