In some cases, you need to read the TXT file from the Flask Web site to the directory. However, creating a file directly in the directory of the Flask Web site is inaccessible. From the site to find some information, and finally found that by writing a method to return TXT content is relatively simple and convenient, but this method is suitable for simple file reading and reading volume is relatively small. The detailed code is as follows:
@app. Route ('/<path> ')
def Today (path):
Base_dir = Os.path.dirname (__file__)
RESP = make_response (open (Os.path.join (base_dir, Path)). Read ())
resp.headers["content-type"]="Text/plan;charset=utf-8"
return RESP
Test method, create a Readm.txt file in the directory you want to catalog.
Run the program, Access/readme.txt, and return the following results:
Extended Knowledge Points:
Since a simple URL instance has been made in the previous code, the URL definition is the same as this one, except that the parameter name is different, as follows:
This time encountered a problem, when I put today's URL definition to the last side, in fact, the access is/<name> this URL, will always return hello xxx, and then put the code of this example to/<name> this interface, run again, Get the right results.
More articles, follow the public number "kick genius"
Read txt file content in Python Web development-flask