web project (1st day)

本文介绍了启动Python Web项目前的准备工作,包括安装所需的技术栈如Django和Celery,搭建项目结构,配置环境以实现异步任务处理及日志记录等关键功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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'))
  1. database setting ===> it’s easy
  2. 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'  # 使用的缓存数据库
  1. 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,
        },
    }
}
  1. 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值