2017-05-26 31 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: