![](/img/trans.png)
[英]How do I add a post method for the api view so that posts can be commented on?
[英]Post API— what are the steps that need to be followed once the code is created so that I can add data into a txt file through this API
我是API的新手,並獲得了創建POST API的任務。 我已經以某種方式創建了代碼。 我想通過post API將數據添加到hello.txt,那么我該怎么做? 這是我的代碼:
import flask
from flask import request, jsonify
app = flask.Flask(__name__)
app.config["DEBUG"] = True
@app.route('/api/v1/resources/messages', methods = ['POST'])
def api_message():
if request.headers['Content-Type'] == 'text/plain':
return "Text Message: " + request.data
elif request.headers['Content-Type'] == 'application/octet-stream':
return "Binary message written!"
elif request.headers['Content-Type'] == 'application/json':
f = open('F:\Asif_Ahmed\Projects\api\hello.txt',"w")
f.write(request.data)
f.close()
return "JSON Message: " + json.dumps(request.json)
else:
return "415 Unsupported Media Type ;)"
app.run()
from flask import Flask, jsonify, render_template, request #import flask library
from flask_basicauth import BasicAuth # import flask library for create basic authentication if needed
from flask_cors import CORS # import flask library Cross-Origin Resource Sharing that is a mechanism that uses additional HTTP headers to tell a browser to let a web application running at one origin (domain) have permission to access selected resources from a server at a different origin
app = Flask(__name__)
CORS(app) #set-up cors for my app
#if you want use basic authentication you need set-up username and password
app.config['BASIC_AUTH_USERNAME'] = 'admin'
app.config['BASIC_AUTH_PASSWORD'] = 'password'
basic_auth = BasicAuth(app)#set-up username and password for my app but in this case I'm not specifying yet in which API use them
@app.route('/api/v1/resources/add_messages', methods=['POST'])#create my POST api
@basic_auth.required# set-up basic authentication for this API, comment out if not needed
def update_credential ():
json_credential=request.get_json()#get the JSON sent via API
print (json_credential["message"])#get the node "message" of my JSON
###########
#code to write in your file, you need write the json_credential["message"]
###########
return ("ok")
if __name__ == '__main__':
app.run(host='0.0.0.0', port=1024, threaded=True)#start my flask app with local_host IP and specific port, if you don't specify the port it will run in the default port
在這種情況下,JSON輸入應為:
{"message":"your text"}
如果有不清楚的地方,請告訴我,我什至在本地嘗試了此代碼,並且JSON順利通過了.....
因此,您需要運行python腳本並查看API是否正在運行,如果您沒有要發送的JSON,並且只是一個簡單的API,可以返回信息,您甚至應該使用Chrome,但在這種情況下,您需要發送一些JSON數據會建議您使用郵遞員。 查看截圖示例:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.