[英]Reading json in pythonanywhere flask app
首先我看到了這個問題。 我的問題是我有一個在 pythonanywhere 上運行的 Flask 應用程序,它從服務器上同一目錄中的 json 文件讀取信息,並收到以下錯誤: Internal Server Error:The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
Internal Server Error:The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
.
我將應用程序簡化為:
from flask import Flask
import json
app = Flask(__name__)
@app.route('/')
@app.route('/index')
def index():
return 'Index'
@app.route('/courses')
def courses():
with open('courses.json', 'r') as f:
these_courses = json.load(f)
return str(these_courses)
如果我轉到索引頁面,我會按預期看到索引,但是如果我嘗試轉到/courses
,則會出現錯誤。整個事情在localhost
上運行良好,然后使用相同的代碼在服務器上出現錯誤,所以我知道從文件中讀取工作正常。 這讓我覺得這可能是 json 與 pythonanywhere 結合所特有的問題。
編輯:可能courses.json
的路徑名有問題,但它在同一個目錄中,所以我覺得應該沒問題,只是一個想法
原來是路徑名問題。 我猜文件需要從根目錄路由。
我跑了:
def courses():
my_dir = os.path.dirname(__file__)
json_file_path = os.path.join(my_dir, 'courses.json')
return json_file_path
找到路徑,然后將函數更改為:
def courses():
with open('/home/username/path/to/file/courses.json', 'r') as f:
these_courses = json.load(f)
return str(these_courses)
現在它起作用了:D
然后為了制作一個在移動項目時不會中斷的更好的版本,我是這樣做的:
def courses():
my_dir = os.path.dirname(__file__)
json_file_path = os.path.join(my_dir, 'courses.json')
with open(json_file_path, 'r') as f:
these_courses = json.load(f)
return str(these_courses)
作為備選:
import pathlib
path = pathlib.Path('courses.json').absolute()
these_courses = json.loads(path.read_text())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.