【问题标题】:Reading json in pythonanywhere flask app在 pythonanywhere 烧瓶应用程序中读取 json
【发布时间】:2015-08-24 15:30:42
【问题描述】:

首先我看到了this question。我的问题是我有一个在 pythonanywhere 上运行的烧瓶应用程序,它从服务器同一目录中的 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..

我将应用程序简化为:

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 的路径名可能有问题,但它在同一个目录中,所以我觉得应该没问题,只是一个想法

【问题讨论】:

  • 不太可能。既然index 方法有效,为什么不导入os 并让它打印os.getcwd() 来验证当前目录实际上是你认为的那样?另外,找出服务器错误日志的位置并查看
  • 我尝试了类似刚才的方法,改变了路径,现在可以了,谢谢!我把我所做的作为答案放在下面

标签: python json flask pythonanywhere


【解决方案1】:

原来是路径名问题。我猜想文件需要从根目录路由。

我跑了:

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)

【讨论】:

    【解决方案2】:

    作为替代方案:

    import pathlib
    
    path = pathlib.Path('courses.json').absolute()
    
    these_courses = json.loads(path.read_text())
    
    

    【讨论】:

      猜你喜欢
      • 2021-01-20
      • 1970-01-01
      • 1970-01-01
      • 2019-09-16
      • 2018-10-09
      • 2019-08-19
      • 2014-02-10
      • 2020-05-09
      • 1970-01-01
      相关资源
      最近更新 更多