分类 Python 下的文章

try:
    with transcation.atomic():
        # 抛出异常,触发事务回滚
        if x != '':
            raise IntegrityError
except IntegrityError:
    handle_exception()

异常必须是DatabaseError或者DatabaseError的子类(比如:IntegrityError)才能够触发回滚。

Django后端支持CORS

django-cors-headers

  • 安装
pip install django-cors-headers

添加django-cors-headersinstalled_apps

INSTALLED_APPS = (
    ...
    'corsheaders',
    ...
)

添加到Django配置文件中的MIDDLEWARE_CLASS元组中


MIDDLEWARE_CLASSES = (
    ...
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...
)
  • 配置

添加允许跨域请求的地址,例如

Example:
    CORS_ORIGIN_WHITELIST = (
        'example.com'
    )

Default:
    CORS_ORIGIN_WHITELIST = ()

参考资料

https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS
http://www.ruanyifeng.com/blog/2016/04/cors.html
https://github.com/ottoyiu/django-cors-headers