我是StackOverflow和Python的新手。我正在尝试制作一个基本应用程序,其中包含我的<form>标记,flask应用程序和.txt。我正在尝试更改值,但是它不起作用,或者我不知道为什么它不起作用。你们中有人可以帮我吗?
Python烧瓶:
from flask import Flask,render_template,flash,request,redirect
import os
app = Flask(__name__)
from lines import get_line
@app.route('/', methods=['POST'])
def change_line():
search_line= "this"
try:
for line in this.input(os.path.join(APP_STATIC, u'line.txt'),inplace=1):
if search_line in line:
x = line.replace(search_line,search_line + "\n" + request.form.get(u'this'))
print (x)
else:
print (x)
except BaseException as e:
print e
return render_template('line.html')
@app.route('/')
def showLine():
line = get_line()
return render_template('line.html', line=line)
if __name__ == '__main__':
app.run()
HTML:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Change the value of this line</title>
</head>
<body>
<form method="post" name="test">
<h4>Chaging Values with POST Method</h4>
<div class="col-sm-9">
<label class="col-sm-3 col-sm-3 control-label">I want to change : </label>
<input type="text" class="form-control" name="address" value="{{ line }}">
</div>
<input type="submit" value="Save Changes!">
</form>
我的.txt文件:
我想改变这个。
它返回“ this”的值。
基本上,当我运行我的应用程序时,当我尝试编辑“ Hello”时它会显示“ this”,这会向我返回错误:
- 在http://127.0.0.1:5000/上运行(按CTRL + C退出)找到行!: 这。127.0.0.1--[2016年10月21日13:09:07]“ GET / HTTP / 1.1” 200-全局名称'this'未定义127.0.0.1--[21 / Oct / 2016 13:09:30 ]“ POST / HTTP / 1.1” 200-
我的输出:请单击此处查看我的输出
很抱歉,如果这是一个愚蠢的问题,或者如果以前已经回答过,但是我一直在寻找答案,但是我一无所获,我尝试了不同的代码,但是没有用,一直在观看youtube视频和所有内容。
如果有人知道该解决方案对我真的很有帮助。
适用于学习和Python School。谢谢!
使用Python 2.7
编辑
我使用以下建议更新了代码,但尚无法正常工作。它不会用replace覆盖我的“ this”。
from flask import Flask,render_template,flash,request,redirect
import os
app = Flask(__name__)
from lines import get_line
import fileinput
@app.route('/', methods=['POST'])
def change_line():
search_line= "this"
try:
for line in fileinput.input(os.path.join(APP_STATIC, u'line.txt'),inplace=1):
if search_line in line:
x = line.replace(search_line,search_line + "\n" + request.form.get(u'asd'))
print (x)
else:
print (x)
except BaseException as e:
print e
return render_template('line.html')
@app.route('/')
def showLine():
line = get_line()
return render_template('line.html', line=line)
if __name__ == '__main__':
app.run(debug=True)
this.input(os.path.join(APP_STATIC, u'line.txt'),inplace=1):
应该
fileinput.input(os.path.join(APP_STATIC, u'line.txt'),inplace=1):
(您还将需要import fileinput
)
您需要更改此设置,因为这this.input
对python毫无意义...它不知道是什么this
...
全局名称“ this”未定义
顺便说一句,您应该app.run(debug=True)
在开发时真正使用
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句