#-*- coding: utf-8 -*-
# module pyparsing.py
#
# Copyright (c) 2003-2019 Paul T. McGuire
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__doc__ = \
"""
pyparsing module - Classes and methods to define and execute parsing grammars
=============================================================================
The pyparsing module is an alternative approach to creating and
executing simple grammars, vs. the traditional lex/yacc approach, or the
use of regular expressions. With pyparsing, you don't need to learn
a new syntax for defining grammars or matching expressions - the parsing
module provides a library of classes that you use to construct the
grammar directly in Python.
Here is a program to parse "Hello, World!" (or any greeting of the form
``"<salutation>, <addressee>!"``), built up using :class:`Word`,
:class:`Literal`, and :class:`And` elements
(the :class:`'+'<ParserElement.__add__>` operators create :class:`And` expressions,
and the strings are auto-converted to :class:`Literal` expressions)::
from pip._vendor.pyparsing import Word, alphas
# define grammar of a greeting
greet = Word(alphas) + "," + Word(alphas) + "!"
hello = "Hello, World!"
print (hello, "->", greet.parseString(hello))
The program outputs the following::
Hello, World! -> ['Hello', ',', 'World', '!']
The Python representation of the grammar is quite readable, owing to the
self-explanatory class names, and the use of '+', '|' and '^' operators.
The :class:`ParseResults` object returned from
:class:`ParserElement.parseString` can be
accessed as a nested list, a dictionary, or an object with named
attributes.
The pyparsing module handles some of the problems that are typically
vexing when writing text parsers:
- extra or missing whitespace (the above program will also handle
"Hello,World!", "Hello , World !", etc.)
- quoted strings
- embedded comments
Getting Started -
-----------------
Visit the classes :class:`ParserElement` and :class:`ParseResults` to
see the base classes that most other pyparsing
classes inherit from. Use the docstrings for examples of how to:
- construct literal match expressions from :class:`Literal` and
:class:`CaselessLiteral` classes
- construct character word-group expressions using the :class:`Word`
class
- see how to create repetitive expressions using :class:`ZeroOrMore`
and :class:`OneOrMore` classes
- use :class:`'+'<And>`, :class:`'|'<MatchFirst>`, :class:`'^'<Or>`,
and :class:`'&'<Each>` operators to combine simple expressions into
more complex ones
- associate names with your parsed results using
:class:`ParserElement.setResultsName`
- find some helpful expression short-cuts like :class:`delimitedList`
and :class:`oneOf`
- find more useful common expressions in the :class:`pyparsing_common`
namespace class
"""
__version__ = "2.3.1"
__versionTime__ = "09 Jan 2019 23:26 UTC"
__author__ = "Paul McGuire <ptmcg@users.sourceforge.net>"
import string
from weakref import ref as wkref
import copy
import sys
import warnings
import re
import sre_constants
import collections
import pprint
import traceback
import types
from datetime import datetime
try:
# Python 3
from itertools import filterfalse
except ImportError:
from itertools import ifilterfalse as filterfalse
try:
from _thread import RLock
except ImportError:
from threading import RLock
try:
# Python 3
from collections.abc import Iterable
from collections.abc import MutableMapping
except ImportError:
# Python 2.7
from collections import Iterable
from collections import MutableMapping
try:
from collections import OrderedDict as _OrderedDict
except ImportError:
try:
from ordereddict import OrderedDict as _OrderedDict
except ImportError:
_OrderedDict = None
try:
from types import SimpleNamespace
except ImportError:
class SimpleNamespace: pass
#~ sys.stderr.write( "testing pyparsing module, version %s, %s\n" % (__version__,__versionTime__ ) )
__all__ = [
'And', 'CaselessKeyword', 'CaselessLiteral', 'CharsNotIn', 'Combine', 'Dict', 'Each', 'Empty',
'FollowedBy', 'Forward', 'GoToColumn', 'Group', 'Keyword', 'LineEnd', 'LineStart', 'Literal',
'PrecededBy', 'MatchFirst', 'NoMatch', 'NotAny', 'OneOrMore', 'OnlyOnce', 'Optional', 'Or',
'ParseBaseException', 'ParseElementEnhance', 'ParseException', 'ParseExpression', 'ParseFatalException',
'ParseResults', 'ParseSyntaxException', 'ParserElement', 'QuotedString', 'RecursiveGrammarException',
'Regex', 'SkipTo', 'StringEnd', 'StringStart', 'Suppress', 'Token', 'TokenConverter',
'White', 'Word', 'WordEnd', 'WordStart', 'ZeroOrMore', 'Char',
'alphanums', 'alphas', 'alphas8bit', 'anyCloseTag', 'anyOpenTag', 'cStyleComment', 'col',
'commaSeparatedList', 'commonHTMLEntity', 'countedArray', 'cppStyleComment', 'dblQuotedString',
'dblSlashComment', 'delimitedList', 'dictOf', 'downcaseTokens', 'empty', 'hexnums',
'htmlComment', 'javaStyleComment', 'line', 'lineEnd', 'lineStart', 'lineno',
'makeHTMLTags', 'makeXMLTags', 'matchOnlyAtCol', 'matchPreviousExpr', 'matchPreviousLiteral',
'nestedExpr', 'nullDebugAction', 'nums', 'oneOf', 'opAssoc', 'operatorPrecedence', 'printables',
'punc8bit', 'pythonStyleComment', 'quotedString', 'removeQuotes', 'replaceHTMLEntity',
'replaceWith', 'restOfLine', 'sglQuotedString', 'srange', 'stringEnd',
'stringStart', 'traceParseAction', 'unicodeString', 'upcaseTokens', 'withAttribute',
'indentedBlock', 'originalTextFor', 'ungroup', 'infixNotation','locatedExpr', 'withClass',
'CloseMatch', 'tokenMap', 'pyparsing_common', 'pyparsing_unicode', 'unicode_set',
]
system_version = tuple(sys.version_info)[:3]
PY_3 = system_version[0] == 3
if PY_3:
_MAX_INT = sys.maxsize
basestring = str
unichr = chr
unicode = str
_ustr = str
# build list of single arg builtins, that can be used as parse actions
singleArgBuiltins = [sum, len, sorted, reversed, list, tuple, set, any, all, min, max]
else:
_MAX_INT = sys.maxint
range = xrange
def _ustr(obj):
"""Drop-in replacement for str(obj) that tries to be Unicode
friendly. It first tries str(obj). If that fails with
a UnicodeEncodeError, then it tries unicode(obj). It then
< returns the unicode object | encodes it with the default
encoding | ... >.
"""
if isinstance(obj,unicode):
return obj
try:
# If this works, then _ustr(obj) has the same behaviour as str(obj), so
# it won't break any existing code.
return str(obj)
except UnicodeEncodeError:
# Else encode it
ret = unicode(obj).encode(sys.getdefaultencoding(), 'xmlcharrefreplace')
xmlcharref = Regex(r'&#\d+;')
xmlcharref.setParseAction(lambda t: '\\u' + hex(int(t[0][2:-1]))[2:])
return xmlcharref.transformString(ret)
# build list of single arg builtins, tolerant of Python ver
基于Python和Django的后台管理框架!.zip
需积分: 0 186 浏览量
更新于2024-04-26
收藏 10.51MB ZIP 举报
在IT行业中,Python和Django是开发者们常用于构建高效、功能丰富的Web应用程序的组合。这个"基于Python和Django的后台管理框架!.zip"文件很可能是为一个毕业设计项目准备的,它包含了实现一个后台管理系统所需的各种资源。下面我们将深入探讨Python和Django在构建后台管理框架中的应用及其相关知识点。
Python是一种高级编程语言,以其简洁的语法和强大的库支持而闻名。在Web开发领域,Python通常作为后端服务器端的语言,负责处理业务逻辑、数据交互和API接口设计。
Django则是一个基于Python的开源Web框架,遵循MVT(Model-View-Template)设计模式,旨在简化Web应用的开发过程。它的核心特性包括ORM(对象关系映射),用于数据库操作;内置的管理员界面,方便数据管理;以及强大的URL路由系统,使得URL设计更加灵活。
1. **模型(Model)**:在Django中,模型是数据库结构的定义,它包含了数据表的字段、类型以及各种约束。通过模型类,你可以直接与数据库进行交互,无需编写SQL语句。例如:
```python
from django.db import models
class User(models.Model):
username = models.CharField(max_length=50)
email = models.EmailField()
password = models.CharField(max_length=128)
```
2. **视图(View)**:视图是处理HTTP请求并返回HTTP响应的部分。它们通常接收用户请求,处理数据,然后调用适当的模板生成HTML响应。Django允许你使用函数式视图或类视图来实现这一过程。
```python
from django.http import HttpResponse
from .models import User
def user_list(request):
users = User.objects.all()
return HttpResponse('<ul>{% for user in users %}<li>{{ user.username }}</li>{% endfor %}</ul>')
```
3. **模板(Template)**:模板负责生成HTML输出,其中可以包含Django模板语言,用于动态渲染数据。Django提供了强大的模板系统,支持变量、控制流、过滤器和继承等特性。
```html
<h1>用户列表</h1>
<ul>
{% for user in users %}
<li>{{ user.username }}</li>
{% endfor %}
</ul>
```
4. **后台管理(Admin)**:Django自带了一个强大的后台管理界面,只需要简单地注册模型,就可以快速创建一个管理站点,供开发者或授权用户对数据进行增删改查操作。这在"毕设"项目中非常实用,可以节省大量时间。
```python
from django.contrib import admin
from .models import User
admin.site.register(User)
```
5. **URL路由(URL Routing)**:Django的URL路由系统允许开发者定义URL模式,将特定的URL映射到相应的视图函数。这样,你可以轻松地创建和管理应用程序的URL结构。
```python
from django.urls import path
from . import views
urlpatterns = [
path('users/', views.user_list, name='user_list'),
]
```
6. **安全与认证**:Django提供了一套完整的用户认证系统,包括登录、注册、权限控制等功能。在后台管理框架中,这些功能至关重要,确保只有授权用户能访问敏感数据。
7. **静态文件与媒体文件**:Django有内置的处理静态文件(如CSS、JavaScript、图片)和用户上传的媒体文件的能力,使得文件管理变得简单。
8. **中间件(Middleware)**:中间件是Django中一种特殊的技术,可以在请求和响应之间插入自定义代码,实现全局的功能,比如日志记录、性能监控等。
9. **部署与性能优化**:了解如何将Django应用部署到生产环境,如Nginx + Gunicorn 或 uWSGI + Nginx 配置,以及如何优化性能,如缓存策略、数据库索引设计等,都是完成一个完整项目的必要步骤。
在"基于Python和Django的后台管理框架!.zip"的压缩包中,可能包含了项目源代码、数据库配置、静态文件、Django设置文件(settings.py)、管理界面的定制化代码等。通过学习和理解这些内容,你不仅能完成毕业设计,还能进一步提升自己的Web开发技能。
JJJ69
- 粉丝: 6368
- 资源: 5917
最新资源
- 直播网站数据采集.zip
- 安卓项目源码Android多线程断点下载
- 语音信号的变调与变速处理实验MATLAB代码
- postgis-2.1.9.tar.gz
- postgis-2.2.6.tar.gz
- postgis-2.3.4.tar.gz
- 真实世界蒙面人脸数据集,口罩人脸数据集.zip
- postgis-2.3.5.tar.gz
- 安卓项目源码Android视频采集+RTSP完整代码(可用)
- postgis-2.4.0.tar.gz
- 神策数据官方Java埋点SDK,是一款轻量级的Java端的数据采集埋点SDK .zip
- postgis-2.4.1.tar.gz
- postgis-2.4.2.tar.gz
- 表格练习数据集+课程复现+作业完成.zip
- 安卓项目源码Android手机的VoIP客户端Sipdroid
- postgis-bundle-pg10-3.2.3x64.zip