NameError:未在python中使用瓶子定义名称“”
所以我对这一切都很陌生,但我会告诉你我有什么问题 因为这是我的任务,所以我尝试使用python、瓶子和.txt创建simpel wiki API。我把我的问题写得更深了,非常感谢你的快速帮助 这是我的.py:NameError:未在python中使用瓶子定义名称“”,python,bottle,nameerror,Python,Bottle,Nameerror,所以我对这一切都很陌生,但我会告诉你我有什么问题 因为这是我的任务,所以我尝试使用python、瓶子和.txt创建simpel wiki API。我把我的问题写得更深了,非常感谢你的快速帮助 这是我的.py: from bottle import route, run, template, request, static_file, redirect def read_articles_from_file(): articles = [] try: my_file = open("
from bottle import route, run, template, request, static_file, redirect
def read_articles_from_file():
articles = []
try:
my_file = open("wiki/articles.txt", "r").close()
content = my_file.read()
for article in content.slpit("/"):
if article != "":
articles.append(article)
return articles
except:
my_file = open("wiki/articles.txt", "w").close()
return articles
@route("/")
def index():
articles_from_file = read_articles_from_file()
return template("./static/index.html", articles = articles_from_file)
@route('/addera', method="POST")
@route('/addera', method="GET")
def save_article():
title = request.forms.get("title")
text = request.forms.get("text")
my_file = open("wiki/articles.txt", "a")
my_file.close()
redirect("/")
@route('/addera')
def show_save_article():
return template("./static/index.html")
@route('/<filename>.css')
def stylesheets(filename):
return static_file('{}.css'.format(filename), root='static')
if __name__ == '__main__':
run(host='localhost', port=8080, debug=True, reloader=True)
else:
print("Något gick fel")
这是我的html索引:
<!doctype html>
<html lang="sv">
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="style.css">
<title>Wiki</title>
</head>
<body>
<div class="header">
<div class="container">
<h1 class="header-heading">Inlämning 5 Wiki</h1>
</div>
</div>
<div class="nav-bar">
<div class="container">
<ul class="nav">
<li><a href="/">Visa alla artiklar</a></li>
<li><a href="/addera">Lägg till artikel</a></li>
</ul>
</div>
</div>
<div class="content">
<div class="container">
<div class="main" id="artiklar">
<h2>Basic wiki</h2>
<hr>
<h3>Alla artiklar</h3>
<ul class="list-unstyled">
% for article in articles:
<li>{{ article }}</li>
% end
</ul>
<hr>
</div>
</div>
</div>
</div>
<div class="footer">
<div class="container">
© Copyright 2017
</div>
</body>
</html>
问题:
为什么会出现这个错误?
您有索引/和addera/addera的路由。在索引路由中,您将文章传递给模板。您没有通过addera路线传递文章,这导致模板中的引用不正确。谢谢,在发布之前,您应该多阅读几次。你能帮我解决我面临的下一个问题吗?当我按下submit时,它没有向.txt添加任何内容。只需创建一个文件并返回IndexyYou不附加到该文件;您只能打开和关闭它。my_file=openwiki/articles.txt,一个my_file.close重定向/