简体   繁体   中英

Trouble accessing private folder in web2py

My web2py application is designed to use a json key from a file stored in my 'private' folder. However, I am having issues accessing this file because request.folder returns None.

This is the bit of code that isn't working for me:

import os
from gluon.globals import Request


def my_function():    

    request = Request()

    json_file = open(os.path.join('request.folder', 'private', 'quote_generator.json')) 

For code inside a web2py application that will be handling HTTP requests, you should not be creating your own Request object -- the web2py execution environment already includes a Request object and populates it with a number of attributes, including request.folder (when you create a new Request object from scratch, it does not have a folder attribute).

If a function in a module needs access to the request object, you should either pass it explicitly as an argument or use the method described here :

from gluon import current

def my_function():
    json_file = open(os.path.join(current.request.folder,
                                  'private', 'quote_generator.json'))

Alternatively, passing request as an argument:

def my_function(request):
    json_file = open(os.path.join(request.folder,
                                  'private', 'quote_generator.json'))

In that case, when calling the above function from a web2py model, controller, or view, you would have to pass in the request object.

Finally, note that when you call os.path.join , you would not put request.folder in quotes, as that would result in the string literal "request.folder" being added to the path.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM