NameError:name''没有在python中使用bottle定义

时间:2017-08-07 20:20:50

标签: python bottle nameerror

所以我对这一切都很陌生,但我会尽力告诉你我有什么问题。

我正在尝试使用python,bottle和.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("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">
           &copy; Copyright 2017
</div>
  </body>
</html>

问题: 为什么我会收到此错误? screen dump

1 个答案:

答案 0 :(得分:2)

您有索引(&#34; /&#34;)和addera(&#34; / addera&#34;)的路线。在索引路由中,您将文章传递给模板。您没有在addera路径中传递文章,这会导致模板中的错误引用。