[英]Web API with Python Flask POST request 405 Method Not Allowed
我正在為我編寫的 python 程序制作 Web API,我正在復制教程
這是API代碼
#!flask/bin/python
from flask import Flask
from flask import make_response
from flask import request
import requests
import json
app = Flask(__name__)
@app.route('/')
def index():
return "Hello, World!"
if __name__ == '__main__':
app.run(debug=True)
@app.errorhandler(404)
def not_found(error):
return make_response(jsonify({'error': 'Not found'}), 404)
@app.route('/5492946838458/index.html', methods=['POST'])
def create_task():
if not request.json or not 'key' in request.json or not 'name' in request.json or not 'text' in request.json or not 'pack' in request.json:
abort(400)
if 'title' in request.json and type(request.json['title']) != unicode:
abort(400)
if 'description' in request.json and type(request.json['description']) is not unicode:
abort(400)
task = {
'key': request.json['key'],
'name': request.json['name'],
'text': request.json['text'],
'pack': request.json['pack']
}
return (200)
這是我要發送到的 URL
https://my.websites.url.here/5492946838458/
和我發送的json數據
{
"key": "key",
"name": "name",
"text": "text",
"pack": "pack"
}
我得到的標題
date: Fri, 04 Sep 2020 17:48:30 GMT
content-length: 0
vary: Origin
accept-ranges: bytes
allow: GET, HEAD, OPTIONS
為什么會發生這種情況,我該如何解決這個問題
我可以看到兩個問題...
此行不應浮動在您的代碼中間。 最后應該是:
if __name__ == '__main__':
app.run(debug=True)
就其當前位置而言,如果您使用python app.py
執行應用程序,則該應用程序將在此時運行。 它之前的路由( index
)將可用,但是在它之后聲明的路由( create_task
)將不可用(直到您殺死服務器 - 當添加后一個路由時,就在python
進程停止之前)。
如果使用flask run
執行,則不會出現此問題,因為if
子句為False。
@app.route('/5492946838458/index.html', methods=['POST'])
對於這個你可能想要:
@app.route('/5492946838458/', methods=['POST'])
這聲明了該路由的 URL。
現在對https://my.websites.url.here/5492946838458/
的請求應該返回一個成功的響應。 對/5492946838458
的請求將返回一個 308 重定向到帶有斜杠的重定向。
我不確定您之前為什么會收到405
。 也許在您的代碼中某處有另一條路線接受請求,但不是方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.