【山大智云项目日志】Seahub+Proset分析(3)

本文详细分析了Django项目的urls.py文件,解释了其作为URL映射表的角色,展示了如何根据URL调用相应视图函数处理请求。同时,介绍了wsgi.py在Django应用与服务器之间的桥梁作用。forms.py文件的讲解集中在自定义表单和数据验证上,展示了如何创建和验证用户注册表单。
摘要由CSDN通过智能技术生成

2021SC@SDUSC

我们继续对Seahub+Proset进行分析。

Seahub

上一次我们主要分析了Seahub的seahub部分,了解了settings.py文件的主要代码,接下来我们继续对其他文件进行分析。

urls.py

urls.py本质上就是一个标准的python文件,这个python文件的作用就是在URL请求和处理该请求的视图函数之间建立一个对应关系,换句话说,它就是一个url请求映射表。我们通过这个文件就可以做到让Django根据不同的url调用不同的代码。url的模式如下:

urlpatterns = [url(正则表达式,view函数,参数,别名,前缀)]

 这些参数的含义依次为:一个正则表达式字符串、一个可调用对象,通常为一个视图函数或一个指定视图函数路径的字符串、可选的要传递给视图函数的默认参数(字典形式)、一个可选的name参数和路径前缀。

因为代码太长,在这里我就不一一展示了,截取了部分代码如下:

 urlpatterns += [
        url(r'^api/v2.1/admin/logs/login/$', LoginLogs.as_view(), name='api-v2.1-admin-logs-login'),
        url(r'^sys/loginadmin/export-excel/$', sys_login_admin_export_excel, name='sys_login_admin_export_excel'),

        url(r'^api/v2.1/admin/logs/file-audit/$', FileAudit.as_view(), name='api-v2.1-admin-logs-file-audit'),
        url(r'^sys/log/fileaudit/export-excel/$', sys_log_file_audit_export_excel, name='sys_log_file_audit_export_excel'),

        url(r'^api/v2.1/admin/logs/file-update/$', FileUpdate.as_view(), name='api-v2.1-admin-logs-file-update'),
        url(r'^sys/log/fileupdate/export-excel/$', sys_log_file_update_export_excel, name='sys_log_file_update_export_excel'),

        url(r'^api/v2.1/admin/logs/perm-audit/$', PermAudit.as_view(), name='api-v2.1-admin-logs-perm-audit'),
        url(r'^sys/log/permaudit/export-excel/$', sys_log_perm_audit_export_excel, name='sys_log_perm_audit_export_excel'),
    ]
if getattr(settings, 'ENABLE_SYSADMIN_EXTRA', False):
    from seahub_extra.sysadmin_extra.views import \
        sys_login_admin_export_excel, sys_log_file_audit_export_excel, \
        sys_log_file_update_export_excel, sys_log_perm_audit_export_excel
    urlpatterns += [
        url(r'^api/v2.1/admin/logs/login/$', LoginLogs.as_view(), name='api-v2.1-admin-logs-login'),
        url(r'^sys/loginadmin/export-excel/$', sys_login_admin_export_excel, name='sys_login_admin_export_excel'),

        url(r'^api/v2.1/admin/logs/file-audit/$', FileAudit.as_view(), name='api-v2.1-admin-logs-file-audit'),
        url(r'^sys/log/fileaudit/export-excel/$', sys_log_file_audit_export_excel, name='sys_log_file_audit_export_excel'),

        url(r'^api/v2.1/admin/logs/file-update/$', FileUpdate.as_view(), name='api-v2.1-admin-logs-file-update'),
        url(r'^sys/log/fileupdate/export-excel/$', sys_log_file_update_export_excel, name='sys_log_file_update_export_excel'),

        url(r'^api/v2.1/admin/logs/perm-audit/$', PermAudit.as_view(), name='api-v2.1-admin-logs-perm-audit'),
        url(r'^sys/log/permaudit/export-excel/$', sys_log_perm_audit_export_excel, name='sys_log_perm_audit_export_excel'),
    ]

 

 其他的代码主要也是urlpatterns,也有getattr函数的应用,主要是用来获取对象的属性值,并通过if语句对url进行筛选。

urls.py的工作过程大概为浏览器发送请求url,然后服务端根据请求的url,在项目的所有应用(包括根目录)的urls.py配置文件中进行查找,如果能匹配到该url,就会将该url交给其对应的视图函数进行处理,负责处理该url的视图函数,会搜集一些业务数据,然后把这些数据,通过 return render(request, '模板文件', 数据); 渲染到前端页面展示给用户。

wsgi.py

此模块包含Django的开发服务器使用的WSGI应用程序以及任何生产WSGI部署。wsgi.py建立了服务器与django程序的桥梁,代码如下:

import os

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "seahub.settings")

# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)

Django 利用DJANGO_SETTINGS_MODULE 环境变量来定位合适的配置模块。它必须包含到配置模块的点式路径。开发环境和生产环境可以配置不同值,这取决于我们是如何组织配置的。这里的seahub就是我们工程的名字。

forms.py

forms.py是Django用来生成form表单代码和验证表单数据是否合法的一个文件, 可以在该文件中创建Form类, 实现自定义表单的功能。Form组件用于对页面进行初始化,生成 HTML 标签,此外还可以对用户提交对数据进行校验(显示错误信息)。在使用之前先导入forms:

from django import forms

 下面我展示一下添加用户的表单代码:

class AddUserForm(forms.Form):
    """
    Form for adding a user.
    """
    email = forms.EmailField()
    name = forms.CharField(max_length=64, required=False)
    department = forms.CharField(max_length=512, required=False)

    role = forms.ChoiceField(choices=[ (i, i) for i in get_available_roles() ])
	
    password1 = forms.CharField(widget=forms.PasswordInput())
    password2 = forms.CharField(widget=forms.PasswordInput())

    def clean_email(self):
        if user_number_over_limit():
            raise forms.ValidationError(_("The number of users exceeds the limit."))

        email = self.cleaned_data['email']
        try:
            user = User.objects.get(email=email)
            raise forms.ValidationError(_("A user with this email already exists."))
        except User.DoesNotExist:
            return self.cleaned_data['email']

    def clean_name(self):
        """
        should not include '/'
        """
        if "/" in self.cleaned_data["name"]:
            raise forms.ValidationError(_("Name should not include '/'."))

        return self.cleaned_data["name"]


    def clean(self):
        """
        Verifiy that the values entered into the two password fields
        match. Note that an error here will end up in
        ``non_field_errors()`` because it doesn't apply to a single
        field.

        """
        if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
            if self.cleaned_data['password1'] != self.cleaned_data['password2']:
                raise forms.ValidationError(_("The two passwords didn't match."))
        return self.cleaned_data

上面代码通过自定义函数和if语句实现了用户信息的校验,如果失败还会有相应的Error信息,这样就可以实现校验功能。

上述是我对seahub的其他部分文件的分析,之后我还会继续对seahub的其他部分以及proset进行分析。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值