Git Product home page Git Product logo

flask-peewee's Introduction

This package is in maintenance-only mode!

I'm sorry to announce that flask-peewee will now be in maintenance-only mode. This decision is motivated by a number of factors:

  • Flask-Admin provides a superior admin interface and has support for peewee models.
  • Flask-Security and Flask-Login both provide authentication functionality, and work well with Peewee.
  • Most importantly, though, I do not find myself wanting to work on flask-peewee.

I plan on rewriting the Database and REST API portions of flask-peewee and repackaging them as a new library, but flask-peewee as it stands currently will be in maintenance-only mode.

flask-peewee

provides a layer of integration between the flask web framework and the peewee orm.

batteries included:

  • admin interface
  • authentication
  • rest api

requirements:

check out the documentation.

admin interface

influenced heavily by the django admin, provides easy create/edit/delete functionality for your project's models.

image

rest api

influenced by tastypie, provides a way to expose a RESTful interface for your project's models.

curl localhost:5000/api/user/
{
  "meta": {
    "model": "user",
    "next": "",
    "page": 1,
    "previous": ""
  },
  "objects": [
    {
      "username": "admin",
      "admin": true,
      "email": "",
      "join_date": "2011-09-16 18:34:49",
      "active": true,
      "id": 1
    },
    {
      "username": "coleifer",
      "admin": false,
      "email": "[email protected]",
      "join_date": "2011-09-16 18:35:56",
      "active": true,
      "id": 2
    }
  ]
}

installing

I recommend installing in a virtualenv. to get started:

# create a new virtualenv
virtualenv --no-site-packages project
cd project/
source bin/activate

# install this project (will install dependencies as well)
pip install flask-peewee

example app

the project ships with an example app, which is a silly twitter clone. to start the example app, cd into the "example" directory and execute the run_example.py script:

cd example/
python run_example.py

if you would like to test out the admin area, log in as "admin/admin" and navigate to:

http://127.0.0.1:5000/admin/

you can check out the REST api at the following url:

http://127.0.0.1:5000/api/message/

flask-peewee's People

Contributors

ajduncan avatar coleifer avatar cpbotha avatar dedan avatar dersphere avatar dirkk0 avatar gobelinus avatar imbolc avatar jabbalaci avatar jcb-k avatar jhorman avatar johtso avatar markpasc avatar medwards avatar ppjet6 avatar yigitbey avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

flask-peewee's Issues

IntegerField and DateField defined with null=True don't allow nulls in admin forms

I have 2 fields on user defined as allowing null.

age = peewee.IntegerField(null=True)
birthdate = peewee.DateField(null=True)

In the admin though, when I try to save with these fields empty.

Not a valid integer value
Not a valid date value

Seems like the empty string for date and integer should resolve to null, and be allowed.

Error Editing DateField in Admin

When I try to edit a model that has a DateField in flask_peewee-0.5.4, I get the following traceback:

Traceback (most recent call last):
  File "/Users/jonanin/dev/mobile/picturegame/server/env/lib/python2.7/site-packages/flask/app.py", line 1701, in __call__
    return self.wsgi_app(environ, start_response)
  File "/Users/jonanin/dev/mobile/picturegame/server/env/lib/python2.7/site-packages/flask/app.py", line 1689, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/Users/jonanin/dev/mobile/picturegame/server/env/lib/python2.7/site-packages/flask/app.py", line 1687, in wsgi_app
    response = self.full_dispatch_request()
  File "/Users/jonanin/dev/mobile/picturegame/server/env/lib/python2.7/site-packages/flask/app.py", line 1360, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/Users/jonanin/dev/mobile/picturegame/server/env/lib/python2.7/site-packages/flask/app.py", line 1358, in full_dispatch_request
    rv = self.dispatch_request()
  File "/Users/jonanin/dev/mobile/picturegame/server/env/lib/python2.7/site-packages/flask/app.py", line 1344, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/Users/jonanin/dev/mobile/picturegame/server/env/lib/python2.7/site-packages/flask_peewee/admin.py", line 524, in inner
    return func(*args, **kwargs)
  File "/Users/jonanin/dev/mobile/picturegame/server/env/lib/python2.7/site-packages/flask_peewee/admin.py", line 285, in edit
    form = Form(obj=instance)
  File "/Users/jonanin/dev/mobile/picturegame/server/env/lib/python2.7/site-packages/wtforms/form.py", line 172, in __call__
    return type.__call__(cls, *args, **kwargs)
  File "/Users/jonanin/dev/mobile/picturegame/server/env/lib/python2.7/site-packages/wtforms/form.py", line 219, in __init__
    super(Form, self).__init__(self._unbound_fields, prefix=prefix)
  File "/Users/jonanin/dev/mobile/picturegame/server/env/lib/python2.7/site-packages/wtforms/form.py", line 33, in __init__
    field = unbound_field.bind(form=self, name=name, prefix=prefix, translations=translations)
  File "/Users/jonanin/dev/mobile/picturegame/server/env/lib/python2.7/site-packages/wtforms/fields/core.py", line 298, in bind
    return self.field_class(_form=form, _prefix=prefix, _name=name, _translations=translations, *self.args, **dict(self.kwargs, **kwargs))
  File "/Users/jonanin/dev/mobile/picturegame/server/env/lib/python2.7/site-packages/wtforms/fields/core.py", line 637, in __init__
    super(DateField, self).__init__(label, validators, format, **kwargs)
  File "/Users/jonanin/dev/mobile/picturegame/server/env/lib/python2.7/site-packages/wtforms/fields/core.py", line 613, in __init__
    super(DateTimeField, self).__init__(label, validators, **kwargs)
TypeError: __init__() got an unexpected keyword argument 'class'

I have found that the problem is on this line in forms.py:

    def handle_date(self, model, field, **kwargs):
        return field.name, fields.DateField(**inject_class(kwargs, 'date-widget'))

This ends up passing a "class" kwarg to construct a new wtforms.Field, which is wrong. The class kwarg should be passed to the widget. I fixed it by creating a custom date field:

class CustomDateField(fields.DateField):
    def __call__(self, **kwargs):
        kwargs["class"] = "date-widget"
        return self.widget(self, **kwargs)

This is probably not the best way to fix it, so I didn't oppen a pull request. Just reporting this issue.

Exposing related objects via REST api

Figure out a way to expose foreign-key related objects using the REST api, as well as how to update & create new

  • specify which related models to serialize
  • use the related model's resource class if possible
  • handles POSTs/PUTs/DELETEs
  • arbitrary nesting depth

Self-referential foreign keys in admin listing

Adding a self-referential column to a model causes a maximum recursion error on the model's admin index/listing page. The edit page does work as expected.

class Category(Model):
name = CharField()
parent = ForeignKeyField('self', related_name='children', null=True)

Subclassing ModelAdmin had no effect.

class CategoryAdmin(ModelAdmin):
columns = ('name',)
admin.register(Category, CategoryAdmin)

overridden user tablename (to users) in model's meta not honored by flask_peewee

I have the following in my model, as you suggested in the bug I reported about registering a user table as per the docs in peewee with postgresql.

class User(db.Model, BaseUser):
    username = CharField(unique=True)
    password = CharField()
    email = CharField()
    join_date = DateTimeField(default=datetime.datetime.now)
    active = BooleanField(default=True)
    admin = BooleanField(default=False)

    def __unicode__(self):
        return self.username

    class Meta:
        db_table = 'users' # Postgres reserves user as a keyword

But flask_peewee does not honor the change, in this case I'm running against mysql:

File "/home/watson/mine/env/lib/python2.7/site-packages/flask/app.py", line 1518, in __call__

return self.wsgi_app(environ, start_response)

File "/home/watson/mine/env/lib/python2.7/site-packages/flask/app.py", line 1506, in wsgi_app

response = self.make_response(self.handle_exception(e))

File "/home/watson/mine/env/lib/python2.7/site-packages/flask/app.py", line 1504, in wsgi_app

response = self.full_dispatch_request()

File "/home/watson/mine/env/lib/python2.7/site-packages/flask/app.py", line 1264, in full_dispatch_request

rv = self.handle_user_exception(e)

File "/home/watson/mine/env/lib/python2.7/site-packages/flask/app.py", line 1260, in full_dispatch_request

rv = self.preprocess_request()

File "/home/watson/mine/env/lib/python2.7/site-packages/flask/app.py", line 1387, in preprocess_request

rv = func()

File "/home/watson/mine/env/lib/python2.7/site-packages/flask_peewee/auth.py", line 187, in load_user

g.user = self.get_logged_in_user()

File "/home/watson/mine/env/lib/python2.7/site-packages/flask_peewee/auth.py", line 144, in get_logged_in_user

return self.User.select().where(active=True).get(id=session.get('user_pk'))

File "/home/watson/mine/env/lib/python2.7/site-packages/peewee.py", line 978, in get

obj = self.where(*args, **kwargs).paginate(1, 1).execute().next()

File "/home/watson/mine/env/lib/python2.7/site-packages/peewee.py", line 1082, in execute

self._qr = QueryResultWrapper(self.model, self.raw_execute())

File "/home/watson/mine/env/lib/python2.7/site-packages/peewee.py", line 825, in raw_execute

return self.database.execute(query, params, self.requires_commit)

File "/home/watson/mine/env/lib/python2.7/site-packages/peewee.py", line 252, in execute

res = cursor.execute(sql, params or ())

File "/home/watson/mine/env/lib/python2.7/site-packages/MySQLdb/cursors.py", line 174, in execute

self.errorhandler(self, exc, value)

File "/home/watson/mine/env/lib/python2.7/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler

raise errorclass, errorvalue

ProgrammingError: (1146, "Table 'mine.user' doesn't exist")

Thanks!

foreign key related columns in ModelAdmin derived class?

I am defining a ModelAdmin class, but I need to include foreign-key related objects in the table. Is there a way to achieve this?

These don't work:

class WhateverAdmin(ModelAdmin):
columns = ('whatever', 'whatever.foreign_key',)

or

class WhateverAdmin(ModelAdmin):
columns = ('whatever', 'whatever.foreign_key'.field,)

Thanks,
David

Add to docs?

I'd suggest adding "To run the example application execute the virtualenv stuff, pip install stuff, and then finally python run_example.py".

I haven't used Flask in awhile and didn't se run_example.py immediately.

Password not encrypted when it's added from admin site

I made my custom user class: class User(db.Model, BaseUser), when I add a new user in my app, I call user.set_password() to set it's password, it works great. But when I add a user from the admin site, the password is not encrypted(it seems that it doesn't call set_password).

Consider tablib for import/export/api?

Have you consider integrating tablib for wider import/export or API capabilities in flask-peewee. I thought that the admin interface would benefit from CSV and/or excel support. I can pursue it myself if you didn't want to go down that road. I just thought I'd ask first in case it was something you had already started.

https://github.com/kennethreitz/tablib

Serializer clean_data doesn't work with list elements.

The clean_data function in serializer doesn't call convert_value if you have a list of things as one of your fields.

For example:

obj = {
    'foo': datetime.datetime.now(),
    'items': [{
        'bar': datetime.datetime.now(),
    }]
}

s = Serializer()

s.clean_data(obj)

This will properly handle foo but not bar. It's a pretty simple fix. I can submit a pull request for the changes if you'd like.

rest basic authentication with header

I couldn't find reference to it but, how would you implement basic authentication if my app will be using rest api but not with a browser?

I would like to pass the username and password in the header over an https request. Does your implementation assume it will only be used with a browser?

Say im building a native Iphone app. I will not be loggin them into the site and saving a session cookie. With each request I will place the credentials in the header, how should I go about extracting that information using your authentication system. I would like to use it with the current system in place.

Matt

Can't generate form defaults

Supposedly model_form should be possible to generate defaults for a form like this:

form = model_form(foo, field_args={
            'bar': {'default': 'the default'}
        }) 

And then in the template

{% for field in form %}
                    {{ field }}
                {% endfor %}

But this doesn't work, no errors are given. The default is: peewee.CharField object at 0x15d0f50

auth.py' login.html extends nonexistent base.html

The auth module uses the flask_peewee/templates/login.html which extends base.html, but this base.html does not exist in the flask_peewee module, if I add one to my own project, then the accounts/login works fine... however I think an example or auths own base should exist next to login.html.

I have looked around but I cant find it, and its not in this repo either... the example app tweepee works fine since it has its own base.html under its example/templates.

This can be fixed by letting login not extend base...

Perhaps provide a template argument to Auth so a project can use their own login template?

peewee.db created, regardless of config.

The problem

Regardless of how I configure my app, the DB config is ignored, and peewee.db is always created. Any ideas? The documentation seems to have gaps - I'lm more than happy to update the docs, if I could understand the answer :)

My app.py

from flask import Flask, render_template, redirect, g, request
from models import User, Expense
from flask_peewee.db import Database

DATABASE = {
    'name': 'mydb.db',
    'engine': 'peewee.SqliteDatabase',
    'threadlocals': True
}

DEBUG = True
SECRET_KEY = 'ssshhhh'

app = Flask(__name__)
app.config.from_object(__name__)

# instantiate the db wrapper
db = Database(app)

@app.route("/")
def index():
        render_template('index.html')

if __name__ == "__main__":

    Expense.create_table(fail_silently=True)
    User.create_table(fail_silently=True)
    if not User.select().where(email='[email protected]'):
        user = User(email='[email protected]')
        user.set_password('*********')
        user.is_superuser = True
        user.save()
    app.run(debug=True)

My models.py

import datetime
from peewee import Model, PrimaryKeyField, CharField, DateTimeField, \
    TextField
from flask_peewee.auth import BaseUser


class BaseModel(Model):
    class Meta:
        pass


class User(BaseModel, BaseUser):
    id = PrimaryKeyField()
    email = CharField()
    password = CharField()

    class Meta:
        db_table = 'users'


class Expense(BaseModel):
    id = PrimaryKeyField()
    description = CharField()
    amount = CharField()
    date = TextField()
    created = DateTimeField(default=datetime.datetime.now)

    class Meta:
        db_table = 'expenses'

Docs

Better docs, please

Admin does not handle FloatField

Tried to create a record but I've got this exception:

>>> res = cursor.execute(sql, params or ())
InterfaceError: Error binding parameter 1 - probably unsupported type.

and in the debugger :

>>> params[1]
Decimal('12')

DateTimeField(null=True) causes admin interface to fail

TypeError: FormField cannot take filters, as the encapsulated data is not mutable.

  File "venv/lib/python2.7/site-packages/flask/app.py", line 1358, in full_dispatch_request
    rv = self.dispatch_request()
  File "venv/lib/python2.7/site-packages/flask/app.py", line 1344, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "venv/lib/python2.7/site-packages/flask_peewee/admin.py", line 505, in inner
    return func(*args, **kwargs)
  File "venv/lib/python2.7/site-packages/flask_peewee/admin.py", line 250, in edit
    form = Form(obj=instance)
  File "venv/lib/python2.7/site-packages/wtforms/form.py", line 178, in __call__
    return type.__call__(cls, *args, **kwargs)
  File "venv/lib/python2.7/site-packages/wtforms/form.py", line 224, in __init__
    super(Form, self).__init__(self._unbound_fields, prefix=prefix)
  File "venv/lib/python2.7/site-packages/wtforms/form.py", line 39, in __init__
    field = unbound_field.bind(form=self, name=name, prefix=prefix, translations=translations)
  File "venv/lib/python2.7/site-packages/wtforms/fields/core.py", line 301, in bind
    return self.field_class(_form=form, _prefix=prefix, _name=name, _translations=translations, *self.args, **dict(self.kwargs, **kwargs))
  File "venv/lib/python2.7/site-packages/wtfpeewee/fields.py", line 107, in __init__
    **kwargs
  File "venv/lib/python2.7/site-packages/wtforms/fields/core.py", line 670, in __init__
    raise TypeError('FormField cannot take filters, as the encapsulated data is not mutable.')

(example app) NameError: name 'DateField' is not defined

When running the example app, I got the following error and traceback:

D:\Python27\Lib\site-packages\flask_peewee-0.5.1-py2.7.egg\example>python run_example.py
Traceback (most recent call last):
  File "run_example.py", line 6, in <module>
    import main
  File "D:\Python27\Lib\site-packages\flask_peewee-0.5.1-py2.7.egg\example\main.py", line 4, in <module>
    from admin import admin
  File "D:\Python27\Lib\site-packages\flask_peewee-0.5.1-py2.7.egg\example\admin.py", line 4, in <module>
    from flask_peewee.admin import Admin, ModelAdmin, AdminPanel
  File "..\flask_peewee\admin.py", line 12, in <module>
    from flask_peewee.filters import QueryFilter, lookups_for_field, Lookup, FIELD_TYPES
  File "..\flask_peewee\filters.py", line 36, in <module>
    'datetime': [DateTimeField, DateField],
NameError: name 'DateField' is not defined

And indeed, DateField is not defined when calling from peewee import *. Maybe some deprecated field that's still used in the example?

I had to change the following in filters.py (lines 36 and 38) in order to get the example running:

FIELD_TYPES = {
    'foreign_key': [ForeignKeyField],
    'text': [CharField, TextField],
    'numeric': [PrimaryKeyField, IntegerField, FloatField, DecimalField, DoubleField],
    'boolean': [BooleanField],
    #'datetime': [DateTimeField, DateField],
    'datetime': [DateTimeField],
    #'time': [TimeField],
    'time': [],
}

Customize admin view

Hi,

I'm trying to customize an admin view, but I'm not really sure how to go about it. My desired result is quite close to the default view, so writing a complete new template doesn't really make sense. Is there some way to override certain parts of a template? I can't seem to find it in the docs.

What I'm specifically trying to do is moving a boolean field inline (so there's a published/unpublished switch in a list view), and implementing a video preview for each item. (This model has a field which is an url for either vimeo or youtube, when the user clicks on it I want to open a lightbox with a preview.)

How to get the "current_db"?

Sorry for ask this, but when I create a Database instance "db" in the init file(eg:"app.py" where I init the Application instance,), How to get this db instance in other files? "from app import db" or init a new Database instance everywhere?

How to achieve ForeignKeyField where default is null?

I have tried to get a ForeignKeyField to use null as its default value but nothing I've tried seems to achieve the desired result, which would be that the drop down for the foreign key has an empty space above the rest of the values representing the null.
I've tried null=True and default=None. Is there something special that I need to do beyond this to get the dropdown behavior?

May just be a documentation issue, but it seems like a typical use-case, and I couldn't figure out how to do it.

Thanks!

TypeError 'engine' is invalid keyword

I made a fresh git clone both in a virtualenv and another in my home directory and both would give the same error when I tried to open 127.0.0.0:5000.

TypeError: 'engine' is an invalid keyword argument for this function

how to get working admin user model with login/logout password encryption?

I have a flask-peewee application using 0.5.4 against PostgreSQL. However, the only user that can work with the system is the admin user which is created from python code. The admin interface will allow me to create a user, but the password field is not encrypted in the same way as the python created user and as such, it fails at login with

ValueError: need more than 1 value to unpack

Any ideas? Can you point me to a working example of how user administration is supposed to work?

fail with gevent

when i use flask_peewee with gevent, it will fail, but when i change flask_peewee to pure peewee, it will be ok.

the error is bellow:

Traceback (most recent call last):
  File "build/bdist.macosx-10.7-intel/egg/gevent/wsgi.py", line 114, in handle
    result = self.server.application(env, self.start_response)
  File "/Library/Python/2.7/site-packages/Flask-0.9-py2.7.egg/flask/app.py", line 1701, in __call__
    return self.wsgi_app(environ, start_response)
  File "/Library/Python/2.7/site-packages/Flask-0.9-py2.7.egg/flask/app.py", line 1689, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/Library/Python/2.7/site-packages/Flask-0.9-py2.7.egg/flask/app.py", line 1687, in wsgi_app
    response = self.full_dispatch_request()
  File "/Library/Python/2.7/site-packages/Flask-0.9-py2.7.egg/flask/app.py", line 1362, in full_dispatch_request
    response = self.process_response(response)
  File "/Library/Python/2.7/site-packages/Flask-0.9-py2.7.egg/flask/app.py", line 1564, in process_response
    response = handler(response)
  File "/Library/Python/2.7/site-packages/flask_peewee-0.5.4-py2.7.egg/flask_peewee/db.py", line 48, in close_db
    self.database.close()
  File "build/bdist.macosx-10.7-intel/egg/peewee.py", line 301, in close
    self.adapter.close(self.__local.conn)
  File "build/bdist.macosx-10.7-intel/egg/peewee.py", line 117, in close
    conn.close()
ProgrammingError: closing a closed connection
: Failed to handle request:
  request = 
  application = 

Adding custom Columns and Fields

Adding custom columns (in my case a DateTimeTZ column that also handles a %z timestamp) is fairly easy by subclassing existing Columns, however the admin interface chokes because it doesn't find a reverse lookup for new columns:

Traceback (most recent call last):
  File "/Users/maebert/.virtualenvs/heydayserver/lib/python2.7/site-packages/flask/app.py", line 1701, in __call__
    return self.wsgi_app(environ, start_response)
  File "/Users/maebert/.virtualenvs/heydayserver/lib/python2.7/site-packages/flask/app.py", line 1689, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/Users/maebert/.virtualenvs/heydayserver/lib/python2.7/site-packages/flask/app.py", line 1687, in wsgi_app
    response = self.full_dispatch_request()
  File "/Users/maebert/.virtualenvs/heydayserver/lib/python2.7/site-packages/flask/app.py", line 1360, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/Users/maebert/.virtualenvs/heydayserver/lib/python2.7/site-packages/flask/app.py", line 1358, in full_dispatch_request
    rv = self.dispatch_request()
  File "/Users/maebert/.virtualenvs/heydayserver/lib/python2.7/site-packages/flask/app.py", line 1344, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/Users/maebert/.virtualenvs/heydayserver/lib/python2.7/site-packages/flask_peewee/admin.py", line 525, in inner
    return func(*args, **kwargs)
  File "/Users/maebert/.virtualenvs/heydayserver/lib/python2.7/site-packages/flask_peewee/admin.py", line 236, in index
    lookups, active_lookups = self.get_lookups()
  File "/Users/maebert/.virtualenvs/heydayserver/lib/python2.7/site-packages/flask_peewee/admin.py", line 182, in get_lookups
    for lookup, lookup_name in lookups_for_field(field):
  File "/Users/maebert/.virtualenvs/heydayserver/lib/python2.7/site-packages/flask_peewee/filters.py", line 102, in lookups_for_field
    for lookup in FIELDS_TO_LOOKUPS[INV_FIELD_TYPES[field_class]]
KeyError: <class 'server.models.basemodel.DateTimeTZField'>

Is there an easy way to tell the admin module how to handle custom fields?

default_next_url in auth may not exist for all projects

hi,

in auth the default_next_url to attempt to redirect to after a login/logout is set to 'homepage' but not all sites have a 'homepage' but mostly do have index I believe.

a simple test case to login with only username and password fails due to no such url_for mapping found.

perhaps a better fail error than the werkzeugs BuildError? or try bogh homepage and index ? or resolve by route rather than function?

admin fails on export json

This occurs in the example app after selecting the user table and clicking export json with no changes in the UI:

Debugging middleware caught exception in streamed response at a point where response headers were already sent.
Traceback (most recent call last):
File "/home/watson/flask-peewee/flask_peewee/admin.py", line 466, in generate
for obj in prepared_query:
File "build/bdist.linux-x86_64/egg/peewee.py", line 1092, in iter
return self.execute()
File "build/bdist.linux-x86_64/egg/peewee.py", line 1082, in execute
self._qr = QueryResultWrapper(self.model, self.raw_execute())
File "build/bdist.linux-x86_64/egg/peewee.py", line 824, in raw_execute
query, params = self.sql()
File "build/bdist.linux-x86_64/egg/peewee.py", line 1038, in sql
parsed_query = self.parse_select_query(alias_map)
File "build/bdist.linux-x86_64/egg/peewee.py", line 1010, in parse_select_query
func, col, col_alias = col
ValueError: need more than 2 values to unpack

The same thing occurred in the app I built working from the getting started doc.

Flask_Peewee + Postgres = ModelAdmin page loads whole table into memory (?)

Hi,

My application crashes when I visit a "ModelAdmin page" because something loads all data of the table into memory (pages with tables with few rows work without a problem)

The python postgres driver loads all data of a query into memory so could this be the problem?

I've tried to find the source of the problem but unfortunately wasn't able.

Best regards,
Daniel

API authentication broken by upgrade to flask-peewee-0.3.2

Hiya

I just updated to 0.3.2 and I am now getting 401 errors when I try to post to my rest API. Nothing has changed in my app's code and I looked at the latest documentation and it seems to have the same requirements for authentication.

This is my current code for my rest API.

from flaskext.rest import RestAPI, UserAuthentication

instantiate the user auth

user_auth = UserAuthentication(auth)

create a RestAPI container

api = RestAPI(app, default_auth=user_auth)

register the models

api.register(model1)
api.register(model2)

api.setup()

default BooleanField value not honored by admin or WTF

I have the following code based on the example in the docs:

class User(db.Model, BaseUser):
    username = CharField(unique=True)
    password = CharField()
    email = CharField(unique=True)
    active = BooleanField(default=True)

but when I go to:

http://localhost:5000/admin/user/add/

The active dropdown is set to False. Shouldn't this default to True just like the datetime field defaults to its default value?

Multi thread sqlite

The flask-peewee tutorial should set the check_same_thread = False in the DB config before connecting to the sqlite3 database.

DateField in admin page will raise exception

File "C:\Python27\lib\site-packages\wtforms\fields\core.py", line 613, in init
super(DateTimeField, self).init(label, validators, **kwargs)
TypeError: init() got an unexpected keyword argument 'class'

the reason is this func:

def inject_class(kwargs, *klasses):
    i_class = list(klasses)
    copy = dict(kwargs)
    if 'class' in copy:
        i_class.append(copy.pop('class'))
    copy['class'] = ' '.join(i_class)
    return copy

I have to hack the code like this, but it's not beautity:

forms.inject_class = lambda kwargs, *klasses: dict(kwargs)

can you fix it? thanks~

flask_peewee admin crashes with AttributeError: 'str' object has no attribute 'strftime' on postgresql

I have a model defined in postgres using peewee. I define admin for this model and attempt to access it but it crashes. I wonder if the unknown field type is the culprit? This postgres database uses PostGIS. How can I handle those fields?

class Lot(BaseModel):
    active = BooleanField()
    address1 = CharField()
    address2 = CharField()
    available_spots = IntegerField()
    city = CharField()
    close_time = TimeField()
    ctr_number = IntegerField()
    endpoint = CharField()
    geom = UnknownFieldType()
    hours = CharField()
    is_full = BooleanField()
    keyphrase = CharField()
    keyword = CharField()
    lat = TextField()
    lon = TextField()
    long_name = CharField()
    lot_type = ForeignKeyField(db_column='lot_type_id', rel_model=LotType)
    max_spots = IntegerField()
    open_time = TimeField()
    passcode = IntegerField()
    reserved_spots = IntegerField()
    short_name = CharField()
    spots_last_updated = DateTimeField()
    state = CharField()
    zip = CharField()

    class Meta:
        db_table = 'lot'

Traceback (most recent call last):
  File "/Users/watson/gitlab/parkpgh/new-mobile/.env/lib/python2.7/site-packages/flask/app.py", line 1701, in __call__
    return self.wsgi_app(environ, start_response)
  File "/Users/watson/gitlab/parkpgh/new-mobile/.env/lib/python2.7/site-packages/flask/app.py", line 1689, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/Users/watson/gitlab/parkpgh/new-mobile/.env/lib/python2.7/site-packages/flask/app.py", line 1687, in wsgi_app
    response = self.full_dispatch_request()
  File "/Users/watson/gitlab/parkpgh/new-mobile/.env/lib/python2.7/site-packages/flask/app.py", line 1360, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/Users/watson/gitlab/parkpgh/new-mobile/.env/lib/python2.7/site-packages/flask/app.py", line 1358, in full_dispatch_request
    rv = self.dispatch_request()
  File "/Users/watson/gitlab/parkpgh/new-mobile/.env/lib/python2.7/site-packages/flask/app.py", line 1344, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/Users/watson/gitlab/parkpgh/new-mobile/.env/lib/python2.7/site-packages/flask_peewee/admin.py", line 520, in inner
    return func(*args, **kwargs)
  File "/Users/watson/gitlab/parkpgh/new-mobile/.env/lib/python2.7/site-packages/flask_peewee/admin.py", line 215, in index
    **self.get_extra_context()
  File "/Users/watson/gitlab/parkpgh/new-mobile/.env/lib/python2.7/site-packages/flask/templating.py", line 125, in render_template
    context, ctx.app)
  File "/Users/watson/gitlab/parkpgh/new-mobile/.env/lib/python2.7/site-packages/flask/templating.py", line 107, in _render
    rv = template.render(context)
  File "/Users/watson/gitlab/parkpgh/new-mobile/.env/lib/python2.7/site-packages/jinja2/environment.py", line 894, in render
    return self.environment.handle_exception(exc_info, True)
  File "/Users/watson/gitlab/parkpgh/new-mobile/.env/lib/python2.7/site-packages/flask_peewee/templates/admin/models/index.html", line 1, in top-level template code
    {% extends "admin/models/base_filters.html" %}
  File "/Users/watson/gitlab/parkpgh/new-mobile/.env/lib/python2.7/site-packages/flask_peewee/templates/admin/models/base_filters.html", line 1, in top-level template code
    {% extends "admin/models/base.html" %}
  File "/Users/watson/gitlab/parkpgh/new-mobile/.env/lib/python2.7/site-packages/flask_peewee/templates/admin/models/base.html", line 3, in top-level template code
    {% from 'macros/forms.html' import admin_field %}
  File "/Users/watson/gitlab/parkpgh/new-mobile/.env/lib/python2.7/site-packages/flask_peewee/templates/admin/base.html", line 80, in top-level template code
    {% block content %}{% endblock %}
  File "/Users/watson/gitlab/parkpgh/new-mobile/.env/lib/python2.7/site-packages/flask_peewee/templates/admin/models/index.html", line 17, in block "content"
    {% include "admin/includes/filter_widgets.html" %}
  File "/Users/watson/gitlab/parkpgh/new-mobile/.env/lib/python2.7/site-packages/flask_peewee/templates/admin/includes/filter_widgets.html", line 4, in top-level template code
    {{ field() }}
  File "/Users/watson/gitlab/parkpgh/new-mobile/.env/lib/python2.7/site-packages/wtfpeewee/fields.py", line 31, in __call__
    return super(StaticAttributesMixin, self).__call__(**kwargs)
  File "/Users/watson/gitlab/parkpgh/new-mobile/.env/lib/python2.7/site-packages/wtforms/fields/core.py", line 139, in __call__
    return self.widget(self, **kwargs)
  File "/Users/watson/gitlab/parkpgh/new-mobile/.env/lib/python2.7/site-packages/wtforms/widgets/core.py", line 123, in __call__
    kwargs['value'] = field._value()
  File "/Users/watson/gitlab/parkpgh/new-mobile/.env/lib/python2.7/site-packages/wtfpeewee/fields.py", line 66, in _value
    return self.data and self.data.strftime(self.format) or u''
AttributeError: 'str' object has no attribute 'strftime'

RestAPI includes pagination - I'm not sure it should.

Hi Charles - outstanding work on this btw - the code is great to work with. One thing the RestAPI allows rapid development of JS/Client side apps using libs such as backbone.

Having Pagination in the api seems a bit clunky - the query mechanism is awesome, but I'm not clear as to why pagination (a view decision) should be included in the API layer.

I'll fork and add an option to have no pagination, and ping you a pull request.

Problem with export in admin

there seems to be a problem on line 355 in admin.py

    return render_template(self.templates['export'],
        model_admin=self,
        model=query.model_class,
        query=query,
        filter_form=filter_form,
        field_tree=field_tree,
        active_filters=cleaned,
        related_fields=related,
        sql=query.sql(***** self.db.get_compiler() ******** ),
        **self.get_extra_context()
    )

I haven't dug that deeply but would guess that it is related to your peewee rewrite?

If I removed the db.get_compiler stuff (since that was made in the query-class anyway) it seems to work.

I thought it might be easier for you to fix than me providing a pull request, since I don't know the code.

/t

Deleting row from table in admin causes field named period not found

I have flask-peewee 0.5.4 using PostgreSQL 9.1.4 installed and a model defined with the following table:

class MailingListPeriod(app.db.Model):
    period = peewee.CharField(unique=True)

    def __unicode__(self):
        return unicode(self.period)

When I run the app, I goto admin and add a row for this table. I then try to delete the row. Flask then generates the following error:

AttributeError
AttributeError: Field named period not found

If I introspect the variables in the call stack, it's pretty clear that flask-peewee is trying lookup the period field on a model called keyword not the expected model called mailinglistperiod.

Any ideas?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.