tornado小機能API実装
5666 ワード
0.はじめに
今回pythonのtornadoのapi開発を学び、いくつかの小さな機能を定義しました.特別な証明書を持っている人だけが私たちのapi にアクセスできます.伝送中に を暗号化する必要がある.
tornadoの基本的な使い方は、みんなが自分で勉強する必要があります.簡単な学習サイトを提供します.tornado基礎チュートリアル
1.tornadoのweb端単純コード
self.set_ヘッダー("Content-Type","text/plain")#転送するコンテンツの表示を開始
今回pythonのtornadoのapi開発を学び、いくつかの小さな機能を定義しました.
tornadoの基本的な使い方は、みんなが自分で勉強する必要があります.簡単な学習サイトを提供します.tornado基礎チュートリアル
1.tornadoのweb端単純コード
# coding=utf8
import tornado.ioloop
import tornado.web
import MySQLdb
import base64
from Crypto import Random
from Crypto.Hash import SHA
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5
from Crypto.Signature import PKCS1_v1_5 as Signature_pkcs1_v1_5
from Crypto.PublicKey import RSA
# class MainHandler(tornado.web.RequestHandler):
# def get(self):
# self.write("You requested the main page")
## get post
class StoryHandler(tornado.web.RequestHandler): # class
def get(self): # get ,
self.write("You requested the story ") # ,get
class MainHandler(tornado.web.RequestHandler):
def post(self): # post
mes = rsa_jiemi(self.get_argument('message')) # rsa ,
# self.get_argument('message'), toanado , post
if jianc(mes): #
self.set_ヘッダー("Content-Type","text/plain")#転送するコンテンツの表示を開始
self.write("You wrote " + ver)
else:
self.set_header("Content-Type", "text/plain")
self.write("You don\'t have access to")
##
application = tornado.web.Application([ # ,tornado
(r"/", MainHandler), # , , class
(r"/story/", StoryHandler),
])
## , message
def jianc(test): # , , api
try:
db = MySQLdb.connect('127.0.0.1','root','','webtest')
cursor = db.cursor()
sql = 'select value from test where value = \'%s\''%test
cursor.execute(sql)
results = cursor.fetchall()
db.commit()
db.close()
#print results
return results
except:
db.rollback()
## , rsa
def rsa_jiemi(message): # rsa
random_generator = Random.new().read # ,
with open('master-private.pem') as f: #
key = f.read()
rsakey = RSA.importKey(key)
cipher = Cipher_pkcs1_v1_5.new(rsakey)
text = cipher.decrypt(base64.b64decode(message), random_generator)
return text
if __name__ == "__main__":
application.listen(8888) # api
tornado.ioloop.IOLoop.instance().start() # ,
2.
import requests import base64 from Crypto import Random from Crypto.Hash import SHA from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5 from Crypto.Signature import PKCS1_v1_5 as Signature_pkcs1_v1_5 from Crypto.PublicKey import RSA def main(): user_info = {'message': 'yjy'} # user_info['message'] = rsa(user_info['message']) # r = requests.post("http://192.168.0.33:8888", data=user_info) # #r = requests.get("http://127.0.0.1:8888/story/1") print r.text # def rsa(message): # with open('master-public.pem') as f: key = f.read() rsakey = RSA.importKey(key) cipher = Cipher_pkcs1_v1_5.new(rsakey) cipher_text = base64.b64encode(cipher.encrypt(message)) return cipher_text if __name__ == '__main__': main()