鍍金池/ 問答/Python  Linux  數(shù)據(jù)庫/ 在服務器上用nginx flask uwsgi搭建的應用,在本地測試傳輸數(shù)據(jù)報錯

在服務器上用nginx flask uwsgi搭建的應用,在本地測試傳輸數(shù)據(jù)報錯

在服務器上的代碼如下

from __future__ import unicode_literals
from flask_restful import Api
from flask import Flask,request
import time
import datetime
#########product==========
import json
#####放在11.46庫
import TextDropRepeat as tdr
import pymongo
import numpy as np
from numpy import array

app = Flask(__name__)
app.debug = True
app.config.update(RESTFUL_JSON=dict(ensure_ascii=False))
api = Api(app)

TODOS = {
    'conhashGroup': {'task': []},
    'publishtime': {'task':[]},
    'conhashGroupA': {'task': []},
    'conhashGroupB': {'task': []},
    'conhashGroupC': {'task': []},
    'conhashGroupD': {'task': []},
}

from flask_restful import reqparse
parser = reqparse.RequestParser()
parser.add_argument('task')
@app.route('/')
def hello_world():
    return 'hello world'
    
@app.route('/drop_TextRepeat/', methods=['POST'])
def add_task():
    print (TODOS)
    nowTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    pastTime = (datetime.datetime.now()-datetime.timedelta(days=5)).strftime('%Y-%m-%d %H:%M:%S')
    time_start=time.time()
    print ('開始獲取數(shù)據(jù)')
    ####獲取數(shù)據(jù)
    try:
        
        data1 = request.form.get('data')
        print (1)
    except:
        data1 = request.data
        print (2)
    #print (data1)
    print ('獲取數(shù)據(jù)成功')
    for line in data1.split('\n'):
        if 'DRETITLE' in line:
            title = line.split('#DRETITLE')[1].strip()
        if 'PUBLISHDATE' in line:
            publishdate = line.replace('=','').replace('"','').split('PUBLISHDATE')[1].strip().replace("'","")
    print (publishdate)
    print (title)
    ###轉換64位hash
    ConHash = tdr.simhash(title)
    ####切割4*16hash
    ConHashA = str(ConHash)[0:16]
    ConHashB = str(ConHash)[16:32]
    ConHashC = str(ConHash)[32:48]
    ConHashD = str(ConHash)[48:]

    if ConHashA in TODOS['conhashGroupA']['task']:
        print (3)
        TODOS['conhashGroup']['task'].append(ConHash)
        TODOS['publishtime']['task'].append(publishdate)
        TODOS['conhashGroupA']['task'].append(ConHashA)
        TODOS['conhashGroupB']['task'].append(ConHashB)
        TODOS['conhashGroupC']['task'].append(ConHashC)
        TODOS['conhashGroupD']['task'].append(ConHashD)
        
        index = np.where((pastTime<=array(TODOS['publishtime']['task'])) & (array(TODOS['publishtime']['task'])<nowTime ))[0].tolist()
        TODOS['publishtime']['task'] = np.array(TODOS['publishtime']['task'])[index].tolist()
        TODOS['conhashGroup']['task'] = np.array(TODOS['conhashGroup']['task'])[index].tolist()
        TODOS['conhashGroupA']['task'] = np.array(TODOS['conhashGroupA']['task'])[index].tolist()
        TODOS['conhashGroupB']['task'] = np.array(TODOS['conhashGroupB']['task'])[index].tolist()
        TODOS['conhashGroupC']['task'] = np.array(TODOS['conhashGroupC']['task'])[index].tolist()
        TODOS['conhashGroupD']['task'] = np.array(TODOS['conhashGroupD']['task'])[index].tolist()

    time_end=time.time()
    print ('totally cost',time_end-time_start)
    
    return 'ok'
    
if __name__ == '__main__':
    app.run(host = '0.0.0.0')

uwsgi配置文件如下

[uwsgi]
socket=/tmp/uwsgi.sock
mount=/myapp=/home/nlp/pyfoot/TD/DropText.py
manage-script-name=true
master=true
processes=4
threads=2
stats=127.0.0.1:9191
callable=app
daemonize = /home/nlp/pyfoot/TD/DropText.log

nginx配置如下

# For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /var/run/nginx.pid;

# Load dynamic modules. See /usr/share/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections  1024;
}


http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    server {
       listen       8000; 
       access_log  /home/nlp/pyfoot/TD/DR.log  main;
       server_name  172.22.11.46;
       
  
       location /myapp {
             root /myapp;
             include uwsgi_params;
             #uwsgi_param SCRIPT_NAME/myapp;
             uwsgi_pass unix:/tmp/uwsgi.sock;
       }
}
    

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;
}

當我在本地電腦瀏覽器訪問服務器時如下,正常顯示helloworld
圖片描述

但是通過py腳本post傳輸數(shù)據(jù)時就報錯,代碼如下

import requests

content = {'data':'#DRETITLE 李克強總理訪歐成果惠及企業(yè)及民眾\n#DREFIELD PUBLISHDATE="2018-07-28 04:42:55"'}
r = requests.post('http://172.22.11.46:8000/myapp/drop_TextRepeat/', data=content)

報錯信息如下
圖片描述

python返回值如下

r.text
Out[29]: '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\n<title>404 Not Found</title>\n<h1>Not Found</h1>\n<p>The requested URL was not found on the server.  If you entered the URL manually please check your spelling and try again.</p>\n'

請問大佬,這個是什么情況,瀏覽器中可以訪問成功,說明配置沒啥問題,但是換post接口就報錯,小弟一直想不明白,還請大佬解惑

回答
編輯回答
小眼睛

uwsgi文件 的路徑 配置錯了 具體大家可百度 uwsgi參數(shù)設置

2017年7月16日 03:05