繁体   English   中英

发布API-创建代码后需要遵循哪些步骤,以便我可以通过此API将数据添加到txt文件中

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM