本文主要是介绍web project (1st day),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
what should we do before start our web project
First–install what we need
Ensure which technologies will be used
think about all of them, such as DATABASE, CACHE, WEB FRAMEWORK, CELERY …
so: In python there is we need:
pip install Django
pip install django_redis
pip install redis
pip install celery
pip install pymysql
pip install pillow ===> for image code verification
…. that is now we need, and than we can extension them
Second–Structure is important than you think
Now, We need talk about the Django project
what application will be support?
what we do is good for the project? maybe docs?log?scripts?
how to manage the project?
how to realize ‘celery’?
….
think above all of them, we can deal with them like this:
│ ├── celery_tasks # execute asynchronous tasks
│ ├── docs # project docs
│ ├── logs # project exception log
│ │ └── meiduo.log
│ ├── manage.py
│ └── meiduo_mall
│ ├── apps # applications moudle
│ ├── libs # Third-party libraries
│ ├── settings # online or develop setting
│ │ ├── dev.py
│ │ ├── init.py
│ │ ├── prod.py
│ │ └── pycache
│ │ ├── dev.cpython-36.pyc
│ │ └── init.cpython-36.pyc
│ ├── settings_old.py
│ ├── urls.py
│ ├── utils # SDK support
│ │ ├── exceptions.py
│ │ └── init.py
│ └── wsgi.py
Third–Setting for better programing environment
questions:
how to sava exceptions log?
how connect databases?
how to realize asynchronous tasks?
how to location project easily?
how to handler exception?
now, deal with all questions?
1. sys.path
sys.path.insert(0, os.path.join(BASE_DIR, 'apps'))
- database setting ===> it’s easy
- Setting django-redis for asynchronous tasks
ACHES = {"default": {"BACKEND": "django_redis.cache.RedisCache","LOCATION": "redis://127.0.0.1:6379/0","OPTIONS": {"CLIENT_CLASS": "django_redis.client.DefaultClient",}},"session": {"BACKEND": "django_redis.cache.RedisCache","LOCATION": "redis://127.0.0.1:6379/1","OPTIONS": {"CLIENT_CLASS": "django_redis.client.DefaultClient",}}
}
SESSION_ENGINE = 'django.contrib.sessions.backends.db' # 数据库引擎设置
SESSION_CACHE_ALIAS= 'session' # 使用的缓存数据库
- logging recording
LOGGING = {'version': 1,# 是否禁止其他的logging功能'disable_existing_loggers': False,# 格式化'formatters': {# 详细'verbose': {'format': '%(levelname)s %(asctime)s %(module)s %(lineno)d %(message)s'},# 简单'simple': {'format': '%(levelname)s %(module)s %(lineno)d %(message)s'},},# 过滤器'filters': {'require_debug_true': {'()': 'django.utils.log.RequireDebugTrue',},},# 处理方式'handlers': {# 解释器'console': {'level': 'DEBUG','filters': ['require_debug_true'],'class': 'logging.StreamHandler','formatter': 'simple'},# 保存到文件'file': {'level': 'INFO','class': 'logging.handlers.RotatingFileHandler','filename': os.path.join(os.path.dirname(BASE_DIR), "logs/meiduo.log"), # 日志文件的位置'maxBytes': 300 * 1024 * 1024,'backupCount': 10,'formatter': 'verbose'},},# 定义日志器'loggers': {'django': { # 定义了一个名为django的日志器'handlers': ['console', 'file'],'propagate': True,},}
}
- handler exception
“`
from django.db import DatabaseError
from redis.exceptions import RedisError
from rest_framework.response import Response
from rest_framework.views import exception_handler as drf_exception_handler
from rest_framework import status
import logging
logger = logging.getLogger(‘django’)
def exception_handler(exc, context):
“””
修改rest_framework 中的异常处理 补充redis和数据库处理
:param exc:异常
:param context:异常发现时的上下文 context[‘view’] 可以访问发生异常的视图
:return:
“”“
# Call REST framework's default exception handler first,
# to get the standard error response.
# print('exc', exc)
# print('context', context)
response = drf_exception_handler(exc, context)
view = context['view']# Now add the HTTP status code to the response.
if response is None:# 查看是否存在数据库异常 以及 Redis异常if isinstance(response, DatabaseError) or isinstance(response, RedisError):logger.error('[%s] %s' % (view, exc))response = Response({"message": "服务器内部错误"}, status=status.HTTP_507_INSUFFICIENT_STORAGE)return response
“`
by the way, there you should setting REST_FRAMEWORK in setting.py
这篇关于web project (1st day)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!