sqlalchemy使用上的小tip

Posted in 2017-3-14 6:16 | Category: Python | Tags: django sqlalchemy python

GitHub地址: https://github.com/honmaple/maple-json

sqlalchemy object序列化为json

灵感来源于 Django REST framework

多个实例

posts = Post.query.all()
serializer = Seralizer(posts,many=True)
data = serializer.data

单个实例

post = Post.query.first()
serializer = Seralizer(post,many=False)
data = serializer.data

排除字段

serializer = Seralizer(post,exclude=['title'])

仅包括字段

serializer = Seralizer(post,include=['title'])

关系查询深度

serializer = Seralizer(post,depth=3)
  • depth 默认为2

增加一些自定义的函数

serializer = Serializer(post,extra=['get_post_count'])

Post

class Post(Model):
    ......
    def get_post_count(self):
        return 11

可传递参数的函数

class PostSerializer(Serializer …

django获取当前request

Posted in 2017-1-10 19:3 | Category: Python | Tags: django python

参考链接:

https://blndxp.wordpress.com/2016/03/04/django-get-current-user-anywhere-in-your-code-using-a-middleware/

http://nedbatchelder.com/blog/201008/global_django_requests.html

使用中间件

from __future__ import absolute_import, division, print_function

try:
    from threading import local
except ImportError:
    from django.utils._threading_local import local

_thread_locals = local()

def get_current_request():
    """ returns the request object for this thread """
    return getattr(_thread_locals, "request", None)

def get_current_user():
    """ returns the current user, if exist, otherwise returns None """
    request = get_current_request()
    if request:
        return getattr(request, "user", None)

class ThreadLocalMiddleware(object):
    """ Simple middleware that adds the request object in thread local stor    age."""

    def process_request(self, request):
        _thread_locals.request = request

    def process_response(self, request, response):
        if hasattr(_thread_locals, 'request'):
        del _thread_locals.request
            return response