api应该包含一个名为“将文本写入文件”的函数,并输入一个字符串参数
至于写入磁盘的函数,我没有问题,我实现了代码,我的问题是如何使用python设置restapi。你知道吗
编辑: 这是我的密码:
from flask import (
Flask,
render_template
)
import SocketServer
import SimpleHTTPServer
import re
app = Flask(__name__, template_folder="templates")
@app.route('/index', methods=['GET'])
def index():
return 'Welcome'
@app.route('/write_text_to_file', methods=['POST'])
def write_text_to_file():
f = open("str.txt", "w+")
f.write("hello world")
f.close()
if __name__ == '__main__':
app.run(debug=True)
无论如何,当我尝试测试rest api时: http://127.0.0.1:5000/write_text_to_file
现在我正在尝试测试我的rest api,但是如何让我的代码启动服务器并测试post请求api,这是我的test\u类:
import requests
import unittest
API_ENDPOINT="http://127.0.0.1:5000/write_text_to_file"
class test_my_rest_api(unittest.TestCase):
def test_post_request(self):
"""start the server"""
r = requests.post(API_ENDPOINT)
res = r.text
print(res)
您正在对此url执行
GET
请求,但您已指定此端点只能接受POST
:@app.route('/write_text_to_file', methods=['POST'])
此外,Flask不需要
SocketServer
和SimpleHTTPServer
导入。你知道吗不允许使用该方法,因为Chrome(或任何浏览器)发出GET请求。你知道吗
但是,你把它定义为POST
或者将其更改为GET方法,或者使用POSTMan之类的工具执行其他HTTP调用类型
相关问题 更多 >
编程相关推荐