Question

I've defined a new Column type called File, which should let me store only the file name in the database. Then I would store the actual file in the file system at root+subfolder+name.

File(root, subfolder="", max_length=100,  **kwargs)

The problem I'm having is that I'd like to define the root in a PasteDeploy config file. How do I define this at runtime so I can access the configuration?

Was it helpful?

Solution

To me this sounds like your schema needs some more thought. Even if you implement a custom column type, that type still has to be mapped into SQL column types that your engine supports. For folder and filename, this is most naturally two varchar columns. So why not just use two fields, path and filename, both of type String(256) in your class?

As for the configurable root, this sounds like you want to specify the path relative to this root, so that you can change it only in one place. Having most of your configuration in the database, except for one thing which is stored in a config file, to me is a code smell. I would consider it preferable over that to have the root be a column in some other configuration table, and use a ForeignKey to refer to the root that way.

OTHER TIPS

Why not avoid the complexity of a custom column type and just store the file path as a column and provide some property or hybrid property that can load the file data for you?

class Data(Base):
    path = Column(String)

def myview(request):
    data = Data(path='foo')

    root_path = request.registry.settings['data_root']
    with open(os.path.join(root_path, data.path), 'rb') as fp:
        file_data = fp.read()
    # ...

Obviously you could wrap some of that functionality into a method on Data if you wanted.

Anyway the way to access INI settings is one of the following:

  1. during application startup from the settings/config objects.
  2. during a request you can pass the setting in from request.registry.settings.
  3. during a request you can access the active request via pyramid.threadlocal.get_current_request() and from there you can get the settings.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top