导致字符串写入fi的HTTP端点

2024-04-26 22:47:41 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我得到以下错误: enter image description here

现在我正在尝试测试我的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)

另外,当使用postman运行我的请求时,我得到了内部\u服务器\u错误: enter image description here


Tags: to函数代码texttestimportrestapi
2条回答

您正在对此url执行GET请求,但您已指定此端点只能接受POST

@app.route('/write_text_to_file', methods=['POST'])

此外,Flask不需要SocketServerSimpleHTTPServer导入。你知道吗

不允许使用该方法,因为Chrome(或任何浏览器)发出GET请求。你知道吗

但是,你把它定义为POST

@app.route('/write_text_to_file', methods=['POST'])

或者将其更改为GET方法,或者使用POSTMan之类的工具执行其他HTTP调用类型

相关问题 更多 >