2017-08-07 30 views
-1

所以我對所有這些都很陌生,但我會試着告訴你我有什麼問題。NameError:name''沒有在python中使用瓶子定義

我想創建一個使用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

回答

2

你有一個索引(「/」)和addera(「/ addera」)的路由。在您的索引路線中,您將文章傳遞給模板。您沒有在addera路由中傳遞文章,導致模板中的引用不正確。

+0

謝謝,在張貼之前應該多讀幾遍。你能幫我解決下一個問題嗎? 當我推送提交時,它不會向.txt添加任何內容。只需創建一個文件並返回索引 –

+0

您不會追加到該文件;你只是打開和關閉它。 –

+0

my_file = open(「wiki/articles.txt」,「a」) my_file.close() redirect(「/」) –