How to run an python file separately in an django project
- 2021-11-01 04:13:09
- OfStack
Sometimes, we might want to write some code in django to test some functionality, and we want to run a separate python file in the django project to do this test.
However, an error will be reported if the command python xxx. py is executed directly to run the python file in the django project
You should load the configuration of django before running this file
import sys
import os
import django
# These two lines are very important to find the root directory of the project. os.path.dirname How many are you going to write depending on the python The number of layers of files to the root directory is determined
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(BASE_DIR)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project_name.settings')
django.setup()
from app.models import Person
if __name__ == "__main__":
all =Person.objects.all().values()
print(all)
Supplement: python file running error _ In django project, run python file separately
If the python file involves code such as a database, running the python file alone will report an error
django.core.exceptions.ImproperlyConfigured:
Requested setting MEDIA_ROOT, but settings are not configured.
You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
Method 1:
You need to run the python file in manage. py shell.
1. Enter shell
Open terminal for django and enter python manage. py shell
2. Run the python file
% run file path
e.g.
%run ./spider/spider_selenium/spider_main_selenium.py
Method 2:
Add at the program entrance:
# import sys; These two lines may not be added unless auto_sale_spider The documents are somewhere else # sys.path.append('../../') # NoQA import os;
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "auto_sale_spider.settings") # "auto_sale_spider.settings" Replace with setting File location
import django;
django.setup() # NoQA
Note 1 must be added to the top of the python file, at least above from models import *
To be on the safe side, it should still be added to the top
e.g.
# coding=utf-8
import os;
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "auto_sale_spider.settings") # NoQA
import django;
django.setup() # NoQA
from spider.models import *
import sys
from html_downloader_selenium import HtmlDownloader
from html_parser_selenium import HtmlParser
import logging
from spider.controller import *
reload(sys)
sys.setdefaultencoding('utf-8')