Python 18 Day

Django

基本操作

  1. 创建一个 Django 项目: django-admin startproject sitename
  2. 创建一个 app: python manage.py startapp web
  3. 运行: python manage.py runserver 127.0.0.1:8000

Django 处理请求流程

  1. 在 settings.py 中添加创建的 app
  2. urls.py 映射 URLpattern: URLpattern --> app.func
  3. views.py 中 使用 render() 渲染模板 (templates) 并返回结果
  4. 配置静态文件
    1. 在 django 项目中创建 static 作为静态文件夹
    2. 在 settings.py 中添加静态文件目录路径
    3. STATIC_URL = ‘/static/‘
      STATICFILES_DIRS = (
          os.path.join(BASE_DIR, ‘static‘),
      )
    4. 在模板中引用
    5. <script src="/static/xxx.js"></script>

Views and URLconfs

To design URLs for an application, you create a Python module called a URLconf. Like a table of contents for your app, it contains a simple mapping between URL patterns and your views.

urls.py

from django.conf.urls import url
from cmdb import views

urlpatterns = [
    url(r‘^index/‘, views.index), # mapping URL patterns and views
]

views.py

a view is responsible for doing some arbitrary logic, and then returning a response.

from django.shortcuts import HttpResponse

def index(request):
    return HttpResponse(‘hello world‘)

Templates

With Django’s template system, we can separate the design of the page from the Python code itself. A Django template is a string of text that is intended to separate the presentation of a document from its data. Usually, templates are used for producing HTML, but Django templates are equally capable of generating any text-based format.

  • Any text surrounded by a pair of braces (e.g., {{ person_name }}) is a variable.
  • Any text that’s surrounded by curly braces and percent signs (e.g., {% if ordered_warranty %}) is a template tag.
    • for tag:
    • {% for item in item_list %}
          <li>{{ item }}</li>
      {% endfor %}
    • if tag:
    • {% if ordered_warranty %}
          <p>Your warranty information will be included in the packaging.</p>
      {% else %}
          <p>You didn‘t order a warranty, so you‘re on your own when
          the products inevitably stop working.</p>
      {% endif %}
    • filter
    • <p>Thanks for placing an order from {{ company }}. It‘s scheduled to
      ship on {{ ship_date|date:"F j, Y" }}.</p>

      In this example, {{ ship_date|date:"F j, Y" }}, we’re passing the ship_date variable to the date filter, giving the date filter the argument "F j, Y".

Here is the most basic way you can use Django’s template system in Python code:

  1. Create a Template object by providing the raw template code as a string.
  2. Call the render() method of the Template object with a given set of variables (the context). This returns a fully rendered template as a string, with all of the variables and template tags evaluated according to the context.
  3. from django.shortcuts import render
    
    USER_INPUT = {}
    
    def index(request):
        """get submit"""
        if (request.method == ‘post‘):
            user = request.POST.get(‘user‘, None) # None is default value
            email = request.POST.get(‘email‘, None)
            temp = {‘user‘: user, ‘email‘: email}
            USER_INPUT.append(temp)
        """    template loading: t = template.Template(‘My name is {{ name }}.‘)    context creation: c = template.Context({‘name‘: ‘Adrian‘})    template rendering: t.render(c)    HttpResponse creation    """
        return render(request, ‘index.html‘, {‘data‘: USER_INPUT})

render()

Django provides a shortcut that lets you

1. load a template 加载模板

2. render it and return an HttpResponse 渲染

all in one line of code.

Models

Django’s database layer.

models.py

from django.db import models

# Create your models here.

class UserInfo(models.Model):
    user = models.CharField(max_length=32)
    email = models.CharField(max_length=32)

create databases:

python manage.py makemigrations

python manage.py migrate

509 garyyang:mysite_django$ python3 manage.py makemigrations
Migrations for ‘cmdb‘:
  cmdb/migrations/0001_initial.py:
    - Create model UserInfo
511 garyyang:mysite_django$ python3 manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, cmdb, contenttypes, sessions
Running migrations:
  Rendering model states... DONE
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying cmdb.0001_initial... OK
  Applying sessions.0001_initial... OK
时间: 2024-11-09 07:21:37

Python 18 Day的相关文章

LPTHW 笨方法学python 18章

看完18章以后,发现第一个练习中,使用了*args读取全部的的输入参数作为一个元组,但是在他的练习中只给了两个变量去赋值,当用户不清楚这个函数的定义时,就可能会给出过多的变量进这个函数,那么就会出现如下错误: ValueError: too many values to unpack 也就是所谓的解包错误,给出的值太多了. 那么为了杜绝这种情况,我取巧解决了下.就是我把元组改变成一个列表,然后补了2位进去. 如果他给的变量少了也没关系,我能补齐.可能太搓了,以后有好的思路再来补齐. def pr

[LeetCode][Python]18: 4Sum

# -*- coding: utf8 -*-'''__author__ = '[email protected]' 18: 4Sumhttps://oj.leetcode.com/problems/4sum/ Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target?Find all unique quadruplets in the array

Python 18 约束和异常处理

约束和异常 1.类的约束 提取父类. 然后在子类中定义好方法. 在这个方法中什么都不用干. 就抛一个异 常就可以了. 这样所有的子类都必须重写这个方法. 否则. 访问的时候就会报错 使用元类来描述父类. 在元类中给出一个抽象?法. 这样子类就不得不给出抽象 方法的具体实现. 也可以起到约束的效果. 方法一 ↓↓↓ def login(self): raise Exception("你没有实现login?法()") class Normal(Base): def login(self):

Python自动化运维课程学习--Day3

本文为参加老男孩Python自动化运维课程第三天学习内容的总结. 大致内容如下: 1.文件操作 2.字符编码转码相关操作 3.函数 0.关于本文中所有运行Python代码的环境: --操作系统:Ubuntu 16.10 (Linux 4.8.0) --Python版本:3.5.2 python2.7.12 --Python IDE: PyCharm 2016.3.2 一.文件操作: 1.文件操作流程:以只读.写(覆盖写).追加写.读写.追加读写.二进制读写等模式打开文件 ==> 得到文件句柄,并

python协程函数、递归、匿名函数与内置函数使用、模块与包

目录: 协程函数(yield生成器用法二) 面向过程编程 递归 匿名函数与内置函数的使用 模块 包 常用标准模块之re(正则表达式) 一.协程函数(yield生成器用法二) 1.生成器的语句形式 a.生成器相关python函数.装饰器.迭代器.生成器,我们是如何使用生成器的.一个生成器能暂停执行并返回一个中间的结果这就是 yield 语句的功能 : 返回一个中间值给调用者并暂停执行. 我们的调用方式为yeild 1的方式,此方式又称为生成器的语句形式. 而使用生成器的场景:使用生成器最好的场景就

python生成RSS(PyRSS2Gen)

既然能够用python解析rss,那么也顺带研究下生成rss. 其实很简单,只是生成一个比较特殊点的xml文档而已. 这里我使用了PyRss2Gen,用法很简单,看代码就知道了,如下: 1 import datetime 2 import PyRSS2Gen 3 4 rss = PyRSS2Gen.RSS2( 5 title = "Andrew's PyRSS2Gen feed", 6 link = "http://www.dalkescientific.com/Python

python基础之继承组合应用、对象序列化和反序列化,选课系统综合示例

继承+组合应用示例 1 class Date: #定义时间类,包含姓名.年.月.日,用于返回生日 2 def __init__(self,name,year,mon,day): 3 self.name = name 4 self.year=year 5 self.mon=mon 6 self.day=day 7 def tell_birth(self): 8 print('%s:%s-%s-%s'%(self.name,self.year,self.mon,self.day)) 9 10 11

Python Json序列化与反序列化

在python中,序列化可以理解为:把python的对象编码转换为json格式的字符串,反序列化可以理解为:把json格式字符串解码为python数据对象.在python的标准库中,专门提供了json库与pickle库来处理这部分. json的dumps方法和loads方法,可实现数据的序列化和反序列化.具体来说,dumps方法,可将json格式数据序列为Python的相关的数据类型:loads方法则是相反,把python数据类型转换为json相应的数据类型格式要求.在序列化时,中文汉字总是被转

python 机器人

1 #!/usr/bin/env python 2 #coding:utf-8 3 4 dict={ 5 'Hello' :'hello', 6 'Nice to meet you' :'Nice to meet you,too', 7 'Which fruit do you like ': 'apple', 8 'how old are you ':'23', 9 'You are handsome':'Thanks' 10 } 11 12 #T train,训练机器人对话 13 #c cha