简体   繁体   中英

HTTP endpoint that causes string to write to a file

the api should include one function called "write text to file" and inputs a string parameter

as for the function to write to the disk I have no problem and I implemented the code my problem is how to set the rest API using python.

EDIT: this is my code:

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)

anyhow when I try to test my rest api: http://127.0.0.1:5000/write_text_to_file

I am getting the following error: 在此处输入图片说明

Now I'm trying to test my rest-api , however how can I make my code to start the server and to the test the post request api, this is my test_class:

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)

also when runnning my request using postman I am getting internal_server_error: 在此处输入图片说明

You're doing a GET request for this url, but you've specified that this endpoint can only accept POST :

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

Also, the SocketServer and SimpleHTTPServer imports are not needed with Flask.

The method is not allowed because Chrome (or any browser) makes GET requests.

Whereas, you defined it as POST

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

Either change it to a GET method, or use a tool such as POSTMan to perform other HTTP call types

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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