python 前后端分離 簡單的數據庫返回接口


 
        

 

1.使用node http-server 起本地服務器  或者打開nginx 直接用nginx的默認頁面也可以 (用下面的html文件替換nginx下html文件夾下的index.html)

http-server -p 8888

然后在瀏覽器打開 localhost:8888 打開頁面 
jQuery ajax 請求數據 

<!DOCTYPE html>
<html>
<head>
    <title>node</title>
</head>
<body>
    <p id="text">jquery 請求數據</p>
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
     <script>
        function get(){
            $.ajax({
                type:'get',
                //url: 'localhost: 8081/docs/',//由於 服務啟動的8888端口請求 8081端口 跨域,用nginx配置跨域
                url: '/docs/',
                success:function(data){
                    $('#text').html(data.data)
                },
                error:function(err){
                 console.log(err);
                }
            })
        }
 
    </script>
    <input type="hidden" id="dat3" value="3">
    <button onClick="get()">請求數據</button>    
</body>
</html>
2.由於 服務啟動的8888/80端口請求 8081端口 跨域,用nginx配置跨域 nginx下載
 server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        access_log  logs/host.access.log;

        location / {
            
            root html;
            index index.html index.htm;
            
        }

        location ^~ /docs/ {
            proxy_pass   http://localhost:8081;
        }
3.python接口文件 新建api.py 在bash下打開  python api.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
import pymysql  #導入 pymysql  
import urllib2
 
import json
from urlparse import parse_qs
from wsgiref.simple_server import make_server
 
  
#打開數據庫連接  
def get_data():
    db= pymysql.connect(host="localhost",user="root",  
        password="123456",db="user",port=3306)  
      
    # 使用cursor()方法獲取操作游標  
    cur = db.cursor()  
      
    #1.查詢操作  
    # 編寫sql 查詢語句  user 對應我的表名  
    sql = "select * from users"  
    # results = 
    try:  
        cur.execute(sql)    #執行sql語句  
      
        results = cur.fetchall()    #獲取查詢的所有記錄  
        # print("id","name","password")  
        #遍歷結果  
        for row in results :  
            id = row[0]  
            name = row[1]  
            password = row[2]  
            # print(id,name,password)  
        return results
    except Exception as e:  
        raise e  
    finally:  
        db.close()  #關閉連接

 
# 定義函數,參數是函數的兩個參數,都是python本身定義的,默認就行了。

def application(environ, start_response):
    # 定義文件請求的類型和當前請求成功的code
    start_response('200 OK', [('Content-Type', 'text/html')])
    # environ是當前請求的所有數據,包括Header和URL,body,這里只涉及到get
    # 獲取當前get請求的所有數據,返回是string類型
    params = parse_qs(environ['QUERY_STRING'])
    # 獲取get中key為name的值
    name = params.get('name', [''])[0]
    no = params.get('no', [''])[0]
    
    # 組成一個數組,數組中只有一個字典
    # dic = {'name': 'name', 'no': 'no'}
   #dic = get_data()

    dic = {'data':[ { 'a' : ['1','2'], 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ]}

    # dic = get();
    return [json.dumps(dic)]
 
 
if __name__ == "__main__":
  url = '127.0.0.1' # 監聽的請求url
    port = 8081 #監聽的端口 只要是8081端口的都會返回數據,下面請求的url加了/docs/ 是nginx 匹配的需要
    # httpd = make_server("0.0.0.0", port, application)
    httpd = make_server(url, port, application)
    print "serving http on port {0}...".format(str(port))
    httpd.serve_forever()

 

配置ok 點擊打開頁面請求下 是不是 是不是請求到數據了
數據自定義 不用再求后端修改接口了。

有問題 歡迎來指點。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM