2017-05-26 33 views
1

我开始学习如何在pythonanywhere工作,所以我有一些问题... 我的web应用程序的结构为:烧瓶pythonanywhere服务器中的文件结构?

/home/mentor/mysite/servidor/ here I've run.py and the folder app 

    inside app there's init.py , views.py and the folders: static,scripts,templates 

我的问题是,在网络里面有一种形式,当有人点击按钮,在views.py中调用脚本中的函数。该功能需要读取.csv文件(我将该文件保存在.../servidor /中)。

但网页不运行,它返回500内部服务器错误,因为OSError:文件b'Names.csv'不存在。 为什么我可以解决这个问题?我需要放置该文件的位置?这是run.py或WSGI配置文件的问题吗?

谢谢!

PD:该代码

在viwes.py

from .scripts.file import function 

@app.route('/func', methods=['POST']) 
def resp(): 
    l=[request.form['d1'].....] 
    f=function(l) 
    ..... 

在脚本文件夹file.py:

import pandas as pd 
    def function(l): 
     df=pd.read_csv('Names.csv') #Here is the problem! 
     ..... 
+0

您能否包含访问该文件的代码? –

+0

@Luis Orduz,我只是把它写下来,没关系?还是你想再看? –

回答

0

的问题是,使用python的工作目录默认情况下任何地方都是主文件夹,所以路径必须从那里开始。

要从wsgi脚本运行时访问它,最安全的事情就是使用操作系统。尝试:

import os 

# ... 

pd.read_csv(os.getcwd(), 'servidor', 'Names.csv') 

你也可以改变工作目录,在pythonanywhere的Web控制台,直接引用的项目(在你的情况'servidor'),并且直接访问再次“Names.csv”。

+0

感谢所有@Luis Orduz,但它不起作用......我也尝试将文件的文件夹更改为其他人,但它不起作用。你认为这是一个WSGI配置问题吗? –

+0

嗨,这可能太晚了,但我改变了答案,为我工作的东西。 –

2

您可以使用__file__打开相对于Python模块的文件。

import os 


def open_here(filename, encoding='UTF-8'): 
    """Open a file in the same directory as this module.""" 
    here = os.path.dirname(os.path.abspath(__file__)) 
    return open(os.path.join(here, filename), encoding=encoding) 


# example snippet 
def foo(): 
    with open_here('my_file') as f: