0

使用Flask和BlueMix部署Web应用程序。有一些我似乎无法弄清的js问题。我在浏览器控制台中不断收到相同的错误。我不知道任何js,所以任何帮助将非常感激!Python Flask,BlueMix,js - 匿名函数

jquery-1.11.1.min.js:4 POST http://newfla.mybluemix.net/ 405 (Method Not Allowed) 
send @ jquery-1.11.1.min.js:4 
m.extend.ajax @ jquery-1.11.1.min.js:4 
(anonymous function) @ demo.js:66 
m.event.dispatch @ jquery-1.11.1.min.js:3 
r.handle @ jquery-1.11.1.min.js:3 

这里是假设(匿名函数)

$.ajax({ 
    type: 'POST', 
    data: { 
    text: $content.val() 
    }, 
    url: '/', 
    dataType: 'json', 
    success: function(response) { 
    $loading.hide(); 

    if (response.error) { 
     showError(response.error); 
    } else { 
     $results.show(); 
     showTraits(response); 
     showTextSummary(response); 
     showVizualization(response); 
    } 

    } 

更新: 我已经尝试了一些不同的东西匹配您的建议。我现在在哪里,有什么想法?

consumer_token = 'aaaaaaaaaaaaaaaaaaaaaaaaa' #substitute values from twitter  website 
consumer_secret = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' 
access_token = '3473558363-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' 
access_secret = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' 

auth = tweepy.OAuthHandler(consumer_token,consumer_secret) 
auth.set_access_token(access_token,access_secret) 

api = tweepy.API(auth) 

class PersonalityInsightsService: 
"""Wrapper on the Personality Insights service""" 

def __init__(self, vcapServices): 
""" 
Construct an instance. Fetches service parameters from VCAP_SERVICES 
runtime variable for Bluemix, or it defaults to local URLs. 
""" 


self.url = "https://gateway.watsonplatform.net/personality-insights/api" 
self.username = "aaaaaa-vvvv-1111-2222-mmmmmmmm" 
self.password = "password" 

if vcapServices is not None: 
    print("Parsing VCAP_SERVICES") 
    services = json.loads(vcapServices) 
    svcName = "personality_insights" 
    if svcName in services: 
     print("Personality Insights service found!") 
     svc = services[svcName][0]["credentials"] 
     self.url = svc["url"] 
     self.username = svc["username"] 
     self.password = svc["password"] 
    else: 
     print("ERROR: The Personality Insights service was not found") 
def getProfile(self, text): 
    """Returns the profile by doing a POST to /v2/profile with text""" 

    if self.url is None: 
     raise Exception("No Personality Insights service is bound to this app") 
    response = requests.post(self.url + "/v2/profile", 
         auth=(self.username, self.password), 
         headers = {"content-type": "text/plain"}, 
         data=text 
        ) 
    try: 
     return json.loads(response.text) 
    except: 
     raise Exception("Error processing the request, HTTP: %d" % response.status_code) 

class DemoService(object): 
    """ 
    REST service/app. Since we just have 1 GET and 1 POST URLs, 
    there is not even need to look at paths in the request. 
    This class implements the handler API for cherrypy library. 
    """ 

    screen_name = "realDonaldTrump" 
    maxnumtweets= 500 

    saveFile = open("static/public/text/en.txt",'a') 
    saveFile.seek(0) 
    saveFile.truncate() 


    for status in  tweepy.Cursor(api.user_timeline,id=screen_name).items(maxnumtweets): 
    print status.text[0:2] + '\n' 
    saveFile = open("static/public/text/en.txt",'a') 

    textyt = status.text 

    texty = ''.join(i for i in textyt if ord(i)<128) 
    saveFile.write(texty.encode('utf-8')+'\n'+'\n') 
    saveFile.close() 

def __init__(self, service): 
    self.service = service 
    self.defaultContent = None 

    try: 
     contentFile = open("static/public/text/en.txt", "r") 
     self.defaultContent = contentFile.read() 
    except Exception as e: 
     print "ERROR: couldn't read text file: %s" % e 
    finally: 
     contentFile.close() 

def GET(self): 
    return render_template('newin.html', content= self.defaultContent) 




def POST(self, text=None): 
    """ 
    Send 'text' to the Personality Insights API 
    and return the response. 
    """ 
    try: 
     profileJson = self.service.getProfile(text) 
     return json.dumps(profileJson) 
    except Exception as e: 
     print "ERROR: %s" % e 
     return str(e) 


@app.route('/') 
def main(): 
    return render_template('index.html') 

@app.route('/getpost', methods=['GET', 'POST']) 
def new(): 
    personalityInsights = PersonalityInsightsService(os.getenv("VCAP_SERVICES")) 
c = DemoService(personalityInsights) 
if request.method == 'GET': 
    return c.GET() 
elif request.method == 'POST': 
    return c.POST() 
+0

好像您正在尝试使用Personality Insights。看看python-sdk:https://github.com/watson-developer-cloud/python-sdk/blob/master/examples/personality_insights_v2.py –

+0

谢谢,德语!我认为这里的问题是我对樱桃的不熟悉程度。我试图将其转换为基于Flask的应用程序,我的问题是我无法弄清楚如何启动POST。 – Beezley

+0

看看这个使用文本到语音服务的Flash应用程序https://github.com/watson-developer-cloud/text-to-speech-python –

回答

4

这不是Javascript问题。提供根URL的查看功能未配置为接受POST请求。响应代码405 (这里的方法是POST而不是GETPUTDELETEOPTIONSHEAD等..

我可以用一个非常简单的Hello World应用瓶重新创建它

app.py:

from flask import Flask 

app = Flask(__name__) 

@app.route('/') 
def hello_world(): 
    return 'Hello World' 

if __name__ == '__main__': 
    app.run(debug=True) 

运行在命令行该应用(将在http://localhost:5000/被提供):

python app.py 

,然后试图发布针对它从另一终端(使用requests库):

import requests 

response = requests.post('http://localhost:5000/', data='') 

打印响应将产生:

<Response [405]> 

注意405 - 相同的响应代码你收到了,方法不允许。您需要明确定义,你希望你的瓶的意见通过更新app.route装饰使用比GET其他任何方法:一般来说,然而

@app.route('/', methods=['GET', 'POST']) 
def hello_world(): 
    return 'Hello World' 

,你要实现不同的功能,如果一个客户端执行POST代替一个GET。您可以通过查看request.method做到这一点(你还需要进口request):

from flask import Flask, request 

app = Flask(__name__) 

@app.route('/', methods=['GET', 'POST']) 
def hello_world(): 
    if request.method == 'GET': 
     return 'You GOT hello world' 
    elif request.method == 'POST': 
     return 'You POSTed hello world' 

if __name__ == '__main__': 
    app.run(debug=True) 

如果您想了解更多关于不同的HTTP方法,它们被定义here

+0

*我的评论太长,所以请看第二个答案,谢谢*。 – Beezley