web project (1st day)

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

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

INFO:ResourceManager:服务器运行中: http://localhost:8888 INFO:tornado.access:304 GET / (::1) 5.00ms INFO:tornado.access:101 GET /ws (::1) 2.00ms ERROR:root:Error processing C:\Users\21904\Desktop\安服学习视频\IP地址详解.rar: name 'time' is not defined ERROR:root:Error processing C:\Users\21904\Desktop\安服学习视频\windows用户管理和权限管理.rar: name 'time' is not defined ERROR:root:Error processing C:\Users\21904\Desktop\安服学习视频\千锋网络安全教程:day02、01-IP地址详解.mp4: name 'time' is not defined ERROR:root:Error processing C:\Users\21904\Desktop\安服学习视频\千锋网络安全教程:day02、02-IP地址详解.mp4: name 'time' is not defined ERROR:root:Error processing C:\Users\21904\Desktop\安服学习视频\千锋网络安全教程:day03、03-用户管理.mp4: name 'time' is not defined ERROR:root:Error processing C:\Users\21904\Desktop\安服学习视频\千锋网络安全教程:day04、01-NTFS权限.mp4: name 'time' is not defined ERROR:root:Error processing C:\Users\21904\Desktop\安服学习视频\千锋网络安全教程:day04、02-NTFS权限.mp4: name 'time' is not defined ERROR:root:Error processing C:\Users\21904\Desktop\安服学习视频\千锋网络安全教程:day04、03-NTFS权限.mp4: name 'time' is not defined ERROR:root:Error processing C:\Users\21904\Desktop\安服学习视频\安服工作量.txt: name 'time' is not defined ERROR:root:Error processing C:\Users\21904\Desktop\安服学习视频\物理层、数据链路层: name 'time' is not defined ERROR:root:Error processing C:\Users\21904\Desktop\安服学习视频\第三部分: name 'time' is not defined ERROR:tornado.application:Uncaught exception GET /files/pool2 (::1) HTTPServerRequest(protocol='http', host='localhost:8888', method='GET', uri='/files/pool2', version='HTTP/1.1', remote_ip='::1') Traceback (most recent call last): File "C:\Users\21904\PycharmProjects\PythonProject\.venv\lib\site-packages\tornado\web.py", line 1848, in _execute result = await result File "C:\Users\21904\PycharmProjects\PythonProject\.venv\resource_manager4\handlers.py", line 176, in get self.render("file_list.html", File "C:\Users\21904\PycharmProjects\PythonProject\.venv\lib\site-packages\tornado\web.py", line 994, in render html = self.render_string(template_name, **kwargs) File "C:\Users\21904\PycharmProjects\PythonProject\.venv\lib\site-packages\tornado\web.py", line 1143, in render_string return t.generate(**namespace) File "C:\Users\21904\PycharmProjects\PythonProject\.venv\lib\site-packages\tornado\template.py", line 362, in generate return execute() File "file_list_html.generated.py", line 121, in _tt_execute _tt_tmp = len(files) # file_list.html:272 NameError: name 'files' is not defined ERROR:tornado.access:500 GET /files/pool2 (::1) 159.98ms INFO:tornado.access:101 GET /ws (::1) 1.00ms INFO:tornado.access:101 GET /ws (::1) 2.00ms INFO:tornado.access:101 GET /ws (::1) 2.00ms ERROR:root:Error processing D:\CloudMusic\Tim Moyo - Unit 731.flac: name 'time' is not defined ERROR:root:Error processing D:\CloudMusic\VipSongsDownload: name 'time' is not defined ERROR:root:Error processing D:\CloudMusic\华晨宇 - 不重逢.flac: name 'time' is not defined ERROR:root:Error processing D:\CloudMusic\华晨宇 - 怪诞心理学.flac: name 'time' is not defined ERROR:root:Error processing D:\CloudMusic\华晨宇 - 普通到不普通的人生.flac: name 'time' is not defined ERROR:root:Error processing D:\CloudMusic\华晨宇 - 永不熄灭的火焰.flac: name 'time' is not defined ERROR:root:Error processing D:\CloudMusic\华晨宇 - 那些我尚未知道的美丽.flac: name 'time' is not defined ERROR:root:Error processing D:\CloudMusic\华晨宇 - 风之海.flac: name 'time' is not defined ERROR:tornado.application:Uncaught exception GET /files/pool1 (::1) HTTPServerRequest(protocol='http', host='localhost:8888', method='GET', uri='/files/pool1', version='HTTP/1.1', remote_ip='::1') Traceback (most recent call last): File "C:\Users\21904\PycharmProjects\PythonProject\.venv\lib\site-packages\tornado\web.py", line 1848, in _execute result = await result File "C:\Users\21904\PycharmProjects\PythonProject\.venv\resource_manager4\handlers.py", line 176, in get self.render("file_list.html", File "C:\Users\21904\PycharmProjects\PythonProject\.venv\lib\site-packages\tornado\web.py", line 994, in render html = self.render_string(template_name, **kwargs) File "C:\Users\21904\PycharmProjects\PythonProject\.venv\lib\site-packages\tornado\web.py", line 1143, in render_string return t.generate(**namespace) File "C:\Users\21904\PycharmProjects\PythonProject\.venv\lib\site-packages\tornado\template.py", line 362, in generate return execute() File "file_list_html.generated.py", line 121, in _tt_execute _tt_tmp = len(files) # file_list.html:272 NameError: name 'files' is not defined ERROR:tornado.access:500 GET /files/pool1 (::1) 8.85ms
08-20
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值