0

I have this 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)

EDIT: MY API includes one functionality which is writing a string to local file system by creating this file. What I want to achieve is to be able to pass a string as part of the api request which could be any string and to write the accepted string into a file, now I'm using hard-coded string which get the job done but I want to achieve the ability to send strings dynamically when using this api to write to file.

tupac shakur
  • 658
  • 1
  • 12
  • 29

1 Answers1

1

Try this:

In postman i posted the string in body as raw. then you can get data using request.data which will be of byte type so you have to use request.data.decode("utf-8")

@app.route('/write_text_to_file', methods=['POST'])
def write_text_to_file():
    if request.method == 'POST':
        print(type(request.data))
        data = request.data.decode("utf-8")
        f = open("str.txt", "w+")
        f.write(data)
        f.close()
    return ''
Nihal
  • 5,262
  • 7
  • 23
  • 41