python 搭建一個http服務的小例子

1、建立Serverhtml

  1.Dos 命令python

    python -m BaseHTTPServer [port]mysql

    

    默認端口是8000,sql

  2.Python 腳本啓動   json

#coding:utf-8
'''
Created on 2018��10��29��

@author: Administrator
'''
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
import MySQLdb
from sqlalchemy import create_engine
import pandas as pd
import json

def handleReq(path):
    print path
    #http://127.0.0.1:8000/itype=90&market=0&code=000001&startNum=0&size=100&shtTQ=1&ptype=0
    #解析URL帶的請求參數
    reqParam = {}
    allReq = path.split('/')
    if len(allReq) > 1:
        req = allReq[1].split('&')
        for strParam in req:
            param = strParam.split('=')
            if len(param) > 1:
                reqParam[param[0]] = param[1]
    
    gpcode = ""
    if reqParam.has_key("market"):
        strMarket = ""
        if reqParam["market"] == '0':
            strMarket = "SZ"
        elif reqParam["market"] == '1':
            strMarket = "SH"
        
        if reqParam.has_key("code"):
            strCode = reqParam["code"]
            
        if len(strMarket) > 0:
            gpcode = strMarket + strCode
            
    conn = create_engine("mysql://root:123456@172.16.8.110/quant?charset=utf8")
    sql = "select * from quant_stk_calc_d_fct_kdj where gscode = 'FCT_KDJ' and gpcode = '{0}' order by ymd desc limit {1},{2}".format(gpcode, reqParam["startNum"], reqParam["size"])
    dfR = pd.read_sql(sql,conn)
    
    datas = []
    for i in range(0,len(dfR["ymd"])):
        date = int(dfR["ymd"][i])
        print type(date)
        k = round(dfR["f1"][i], 4)
        d = round(dfR["f2"][i], 4)
        j = round(dfR["f3"][i], 4)
        dictData = {"iDate":date,"mField":{"K":k, "D":d, "J":j}}
        datas.append(dictData)
    
    return datas
    
class HTTPHandle(BaseHTTPRequestHandler):  
    def do_GET(self):
        if self.path != "/favicon.ico":
            print "path:",self.path

            datas = handleReq(self.path) #處理URL請求參數,根據參數獲取相應數據
            jsonStr = json.dumps(datas)    
            print jsonStr
        
            self.protocol_version = "HTTP/1.1"       
            self.send_response(200)        
            self.send_header("Content-type", "application/json")  
            self.end_headers()     
            self.wfile.write(jsonStr)
            
        
def startServer():
    httpServer = HTTPServer(("127.0.0.1", 8000), HTTPHandle)
    httpServer.serve_forever()
    
if __name__ == '__main__':
    startServer()

  

2、瀏覽器訪問瀏覽器

    服務開啓後,在瀏覽器輸入網址訪問服務器資源服務器

    http://127.0.0.1:8000/itype=90&market=0&code=000001&startNum=0&size=100&shtTQ=1&ptype=0app

 

效果:code

 

BaseHTTPServer模塊說明,參見:http://blog.sina.com.cn/s/blog_9e9f16d10102x7fc.htmlorm

報錯:json 報錯'xxx is not JSON serializable'的處理方法,參見:http://www.javashuo.com/article/p-yvsmspcw-bn.html

 

另參見:https://www.jianshu.com/p/4221c2b835a3

相關文章
相關標籤/搜索