[英]What causes a http request to overwrite the internal buffer created by file.write()?
[英]HTTP endpoint that causes string to write to a file
api應該包含一個稱為“將文本寫入文件”的函數,並輸入一個字符串參數
至於寫入磁盤的功能我沒有問題,我實現了代碼,我的問題是如何使用python設置其余API。
編輯:這是我的代碼:
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)
無論如何,當我嘗試測試我的其余api時: http : //127.0.0.1 : 5000/write_text_to_file
現在,我正在嘗試測試rest-api,但是如何使我的代碼啟動服務器並測試發布請求api,這就是我的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)
您正在對此URL執行GET
請求,但是您已指定此終結點只能接受POST
:
@app.route('/write_text_to_file', methods=['POST'])
另外,Flask不需要SocketServer
和SimpleHTTPServer
導入。
不允許使用此方法,因為Chrome(或任何瀏覽器)發出GET請求。
而您將其定義為POST
@app.route('/write_text_to_file', methods=['POST'])
將其更改為GET方法,或使用POSTMan之類的工具執行其他HTTP調用類型
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.