简体   繁体   中英

How to dynamically populate CORS_ORIGIN_WHITELIST from the database with django-cors-headers?

I am writing a django application where I have a model called Website which contains websites of people. I only allow people who have their websites in my database to use my Django REST API. I am using the django-cors-headers package to whitelist the domains of people: https://github.com/adamchainz/django-cors-headers .

CORS_ORIGIN_WHITELIST variable in settings.py allows me to white list domains as shown in https://github.com/adamchainz/django-cors-headers#cors_origin_whitelist

The problem is that I have to query my models to get the website domains, append them to a list and then put that list into CORS_ORIGIN_WHITELIST . But I can't do that in settings.py because models are loaded after the app starts and settings.py is the one that starts the app.

Does anyone know a way around that? Any suggestions will be appreciated. Thanks in advance.

django-cors-headers has a signal that allows you to decide whether or not to allow the request to pass. The docs show exactly your use case.

Note that CORS_ORIGIN_WHITELIST is also checked by the cors middleware (the signal response doesn't replace the white list), so you can have both: a static whitelist + a dynamic whitelist that depends on the request . You don't need to check the static whitelist in your signal handler.

django-cors-headers also has a setting CORS_ALLOWED_ORIGIN_REGEXES , which comes in handy if your allowed origins can be written as a regex / regular expression.

For example, you could use this to allow wildcard subdomains:

CORS_ALLOWED_ORIGIN_REGEXES = [
    r"^https://\w+\.example\.com$",
]

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