SlideShare a Scribd company logo
Uliweb Cheat Sheet 0.1
作者:limodou@gmail.com
整体介绍
说明:Uliweb 是一个 Python Web 开发框架
开发模式:MVT(Model, View, Template)
项目结构:
project/
apps/
settings.ini
app1/
templates/
xxx.html
settings.ini
views.py
models.py
…
app.yaml
gae_handler.py
fcgi_handler.py
wsgi_handler.py
项目主页:
http://code.google.com/p/uliweb
安装
svn co http://uliweb.googlecode.com/svn/trunk/ uliweb
python setup.py develop
Hello,Uliweb - 第一个 Uliweb 程序
uliweb makeproject Project1
cd Project1
uliweb makeapp Hello
uliweb runserver
在浏览器访问: http://localhost:8000
开发流程
功能开发:创建 App->编辑 views->设置 url|处理 Model|
处理 Form
配置开发:修改 app 的 settings|使用 dispatch
View 基本内容
文件名:views.py, views_xx.py, views_yy.py
def __begin__():
#进入 view 函数之前的处理
def __end__():
#执行 view 函数之后的处理
@expose(‘/’)
def index():
return ‘Hello,world’
@expose(‘/user/<name>’) #expose 中可以定义参数
def user_view(name): #在 view 函数中要定义同名参数
from werkzeug import Response
return Response(‘Hello, world’)#返回一个 Response
Expose 格式
@expose(‘/user/<name>’)
@expose(‘/users’ , default={‘pageno’:0})#可以传入缺省值
@expose(‘/users/<int:pageno>’)#匹配整数
@expose(‘/files/<path:file>’) #匹配/files/之后的内容(含/)
@GET(URL) #只允许 GET 方式
@POST(URL) #只允许 POST 方式
命名 url
@expose(‘/user/<name>’, name=’user_view’)
#反向获取 url_for(’user_view’, name=’test’)
View 的返回值
Response() #from werkzeug import Response
‘Hello’
{} #自动套用同名的模板
json(data)
redirect(new_url)
error(error_message)
others #自动使用 str(others)
可以在 view 中和 template 中直接使用的变量
request #线程安全
response #线程安全
application #当前应用对象
settings #配置对象
json #json 数据
url_for #反向 url 获取
error #出错
redirect #重定向
⊙也可以通过 from uliweb import xx 来导入上面内容
反向 url 获取(url_for)
url_for(‘appname.views.view_func’, **kwargs)
url_for(‘named_url’, **kwargs)
url_for(view_func, **kwargs)
安装 uliweb.contrib.staticfiles 之后,可以使用:
url_for_static(filename) #获得静态文件 url
Template 语法
{{=var}} #escape html chars
{{=func()}} #escape html chars
{{python code}}
{{<< htmlcode}} #unescape html chars
{{if user=='admin':}}
<p>Welcome</p>
{{else:}}
<a href="/login">Login</a>
{{pass}}
{{block content}}<div>default content</div>{{end}}
{{embed var}}
{{include “template.html”}} or {{include var}}
{{extend “template.html”}} or {{extend var}}
安装 uliweb.contrib.template 之后,可以使用:
{{use “template_plugin_name”}}
{{link “js|css”}}
settings.ini 语法
#coding=UTF-8
[GLOBAL]
DEBUG = True
INSTALLED_APPS = [
'uliweb.contrib.staticfiles',
]
MIDDLEWARE_CLASSES = [
'uliweb.orm.middle_transaction.TransactionMiddle'
]
TIME_ZONE = 'UTC'
uliweb 命令行
uliweb 显示全部可用的命令(根据有效的 app 生成)
uliweb runserver 启动开发服务器
uliweb develop 启动开发服务器,同时装入 develop app
uliweb makeproject 创建一个项目
uliweb makeapp 创建一个 app
uliweb makepkg 创建一个 python 的包目录
uliweb shell 进入 shell 环境
uliweb i18n 执行 i18n 的处理
uliweb extracturls 将所有 url 取出放入 urls.py
uliweb exportstatic 将所有静态文件导出到指定目录
uliweb call 调用 app 下的命令
安装 uliweb.contrib.orm 后,可以使用:
uliweb dbinit 执行 app 下的 dbinit.py 程序,进行初始化
uliweb dump dump 出数据库中的数
uliweb load 将 dump 的数据重新装回数据库
uliweb syncdb 自动创建表
uliweb sql 查看 create table 语句
uliewb reset 重新建表
安装 uliweb.contrib.auth 后可以执行:
uliweb createsuperuser 创建超级用户
ORM-settings.ini 设置
[ORM]
DEBUG_LOG = False
AUTO_CREATE = True
CONNECTION = 'sqlite://'
CONNECTION 格式:
#sqlite
‘sqlite:////absolute/path/to/database.txt’
‘sqlite:///d:/absolute/path/to/database.txt’
‘sqlite:///relative/path/to/database.txt’
‘sqlite://’ # in-memory database
‘sqlite://:memory:’ # the same
# postgresql
'postgres://scott:tiger@localhost/mydatabase'
# mysql
'mysql://scott:tiger@localhost/mydatabase'
# oracle
'oracle://scott:tiger@127.0.0.1:1521/sidname'
# oracle via TNS name
'oracle://scott:tiger@tnsname'
# mssql using ODBC datasource names. PyODBC is the
default driver.
'mssql://mydsn'
'mssql://scott:tiger@mydsn'
# firebird
'firebird://scott:tiger@localhost/sometest.gdm'
ORM-Model 定义
from uliweb.orm import *
class Requirement(Model):
req_id = Field(CHAR, max_length=12,)
year = Field(int, required=True)
可用字段(简便方式):
StringProperty Field(str) #vchar
CharProperty Field(CHAR) #char
UnicodeProperty Field(Unicode)#vchar
TextProperty Field(TEXT) #Text
BlobProperty Field(BLOB) #Blob
FileProperty Field(FILE) #vchar,保存文件名
IntegerProperty Field(int) #int
FloatProperty Field(float) #float
BooleanProperty Field(bool) #boolean
DateTimeProperty Field(datetime)#datetime
DateProperty Field(date) #date
TimeProperty Field(time) #time
DecimalProperty Field(DECIMAL)#numeric
关系定义:
Reference
SelfReference
OneToOne
ManyToMany
自定义表属性:
class Note(Model):
__tableame__ = 't_note'#表名
__table_args__ = dict(mysql_charset='utf8')
@classmethod
def OnInit(cls):
Index('my_indx', cls.c.title, cls.c.owner,
unique=True)
Model 属性:
.table #sqlalchemy 中的 Table 对象
.metadate #sqlalchemy 中的 metadata 对象
.c #等同于 model.table.c
.properties #属性列表
._manytomany #manytomany 属性
ORM-实例级操作
class User(Model):
username = Field(CHAR, max_length=20)
year = Field(int)
创建:
user = User(username=’user’, year=20)
user.save()
获取:
user = User.get(1)
user = User.get(User.c.id == 1)
删除:
user.delete()
修改:
user.username = ‘user1’
user.save()
or
user.update(**data)
其它方法:
user.to_dict(*fields)
ORM-表级操作
User.all()
User.filter(User.c.year > 18)
User.remove(condition)
User.count(condition)
ORM-结果集操作
直接返回单表结果集:
User.all()
User.filter()
通过关系返回结果集:
class User(Model):
username = Field(CHAR, max_length=20)
year = Field(int)
class Group(Model):
name = Field(str, max_length=20)
manager = Reference(User,
collection_name=’m_groups’)
users = ManyToMany(User,collection_name=’groups’)
以下方法返回结果集:
user.m_groups #多表结果集
group.users #多表结果集
user.groups #单表结果集
单表结果集方法:
all() #全部,返回结果集
filter() #过滤,返回结果集
order_by() #排序,返回结果集
limit() #限制,返回结果集
offset() #偏移,返回结果集
distinct() #不重复,返回结果集
返回结果:
clear() #清除
count() #计数
one() #单条记录
values() #返回字段列表的[]结果
values_one() #返回字段列表的单条结果
多表结果集方法:
all() #全部,返回结果集
filter() #过滤,返回结果集
order_by() #排序,返回结果集
limit() #限制,返回结果集
offset() #偏移,返回结果集
distinct() #不重复,返回结果集
返回结果:
clear() #清除
count() #计数
one() #单条记录
values() #返回字段列表的[]结果
values_one() #返回字段列表的单条结果
has() #存在
Model-Settings 配置
在 settings.ini 中,如下:
[MODELS]
assignment = 'assignments.models.Assignment'
以后可以通过以下方式获得 Model:
from uliweb.orm import get_model
Assignment = get_model(‘assignment’)
同时可以在定义关系时,使用字符串来表示一个表。
Dispatch 主题
dispatch.call(application, 'startup_installed')
dispatch.call(application, 'startup')
dispatch.call(application, 'prepare_view_env', env)
安装完 uliweb.contrib.orm 后增加:
dispatch.call(model, 'pre_save', instance, created, data,
old_data)
dispatch.call(model, 'post_save', instance, created, data,
old_data)
dispatch.call(model, 'pre_delete', instance)
dispatch.call(model, 'post_delete', instance)

More Related Content

PPTX
Vue.js
PDF
webpack 入門
PDF
從改寫後台 jQuery 開始的 Vue.js 宣告式渲染
PPTX
使用 ASP.NET 5 實戰開發雲端應用程式
PDF
2021.laravelconf.tw.slides3
PPTX
ASP.NET MVC 5 新功能探索
PPTX
進擊的前端工程師:今天就用 JSON Server 自己打造 API 吧!
PDF
Honey's Data Dinner#7 webpack 包達人(入門)
Vue.js
webpack 入門
從改寫後台 jQuery 開始的 Vue.js 宣告式渲染
使用 ASP.NET 5 實戰開發雲端應用程式
2021.laravelconf.tw.slides3
ASP.NET MVC 5 新功能探索
進擊的前端工程師:今天就用 JSON Server 自己打造 API 吧!
Honey's Data Dinner#7 webpack 包達人(入門)

What's hot (20)

PDF
2021laravelconftwslides10
PDF
Vue ithome
PDF
JavaScript Code Quality
PPTX
Spring boot 简介
PPTX
How tovuejs
PDF
動手打造 application framework-twMVC#15
PDF
Angular js twmvc#17
PDF
CodeIgniter 2.0.X
PDF
使用者認證
PDF
現代 IT 人一定要知道的 Ansible 自動化組態技巧 Ⅱ - Roles & Windows
PDF
CRUD 綜合應用
PDF
Gulp.js 自動化前端任務流程
PDF
视图模式
PDF
CRUD 綜合運用
ODP
GNU Build System
PDF
不断归零的前端人生 - 2016 中国软件开发者大会
PPTX
J engine -构建高性能、可监控的前端应用框架
PPTX
J engine -构建高性能、可监控的前端应用框架
PDF
2021laravelconftwslides12
PDF
AngularJS training in Luster
2021laravelconftwslides10
Vue ithome
JavaScript Code Quality
Spring boot 简介
How tovuejs
動手打造 application framework-twMVC#15
Angular js twmvc#17
CodeIgniter 2.0.X
使用者認證
現代 IT 人一定要知道的 Ansible 自動化組態技巧 Ⅱ - Roles & Windows
CRUD 綜合應用
Gulp.js 自動化前端任務流程
视图模式
CRUD 綜合運用
GNU Build System
不断归零的前端人生 - 2016 中国软件开发者大会
J engine -构建高性能、可监控的前端应用框架
J engine -构建高性能、可监控的前端应用框架
2021laravelconftwslides12
AngularJS training in Luster
Ad

Viewers also liked (20)

PDF
Uliweb框架思想与编程
PPTX
01.python介绍
PPTX
Python面向对象开发基础篇
PPT
Algebra I Warm-ups
PPTX
02.python基础
PPTX
01.uliweb介绍
PPT
Uliweb比较与实践 2013
PPTX
03.python工作环境
PPTX
02.uliweb开发入门
PPTX
03.uliweb开发进阶
PPT
Uliweb 快速易用的Python Web Framework
PPTX
04.uliweb更多话题介绍
PPT
Or Sam Opiates &amp; Opioids 04 19 2011
PPTX
Pregnancy with beta thalassemia
PPTX
MANAGEMENT OF HYPEREMESIS GRAVIDARUM
PPTX
Loreal case study
PPTX
HR practices in infosys
PDF
Programme du PLFI 2013
PDF
Stratégie digital-cci-rennes-btob-btoc-2013
PDF
"Génération Y, de A à Z" par MEC Paris
Uliweb框架思想与编程
01.python介绍
Python面向对象开发基础篇
Algebra I Warm-ups
02.python基础
01.uliweb介绍
Uliweb比较与实践 2013
03.python工作环境
02.uliweb开发入门
03.uliweb开发进阶
Uliweb 快速易用的Python Web Framework
04.uliweb更多话题介绍
Or Sam Opiates &amp; Opioids 04 19 2011
Pregnancy with beta thalassemia
MANAGEMENT OF HYPEREMESIS GRAVIDARUM
Loreal case study
HR practices in infosys
Programme du PLFI 2013
Stratégie digital-cci-rennes-btob-btoc-2013
"Génération Y, de A à Z" par MEC Paris
Ad

Similar to Uliweb cheat sheet_0.1 (20)

PDF
Introduction to MVC of CodeIgniter 2.1.x
PPTX
Uliweb设计分享
PDF
Vlog02 [eng sub]什麼是controller和如何在asp.net核心中創建controller?-what is controller ...
PDF
Asp.net mvc網站的從無到有
PDF
[GDG Kaohsiung DevFest 2023] 以 Compose 及 Kotlin Multiplatform 打造多平台應用程式
PDF
Bitbucket pipeline CI
ODP
Clojure cnclojure-meetup
PDF
ASP.NET Core 2.1設計新思維與新發展
PDF
I os 16
PPTX
twMVC#01 | ASP.NET MVC 的第一次親密接觸
PPTX
常用开发工具介绍
PPT
Android应用开发 - 沈大海
KEY
Flex 4.5 action custom component development
PDF
Struts快速学习指南
PDF
一拍一产品背后的故事(React实战)
PDF
使用 Kong 與 GitOps 來管理您企業的 API 呼叫 @ 2024 台灣雲端大會
PDF
rebar erlang 2
PPT
YUIconf2010介绍
PDF
Spring 2.x 中文
PDF
Kissy design
Introduction to MVC of CodeIgniter 2.1.x
Uliweb设计分享
Vlog02 [eng sub]什麼是controller和如何在asp.net核心中創建controller?-what is controller ...
Asp.net mvc網站的從無到有
[GDG Kaohsiung DevFest 2023] 以 Compose 及 Kotlin Multiplatform 打造多平台應用程式
Bitbucket pipeline CI
Clojure cnclojure-meetup
ASP.NET Core 2.1設計新思維與新發展
I os 16
twMVC#01 | ASP.NET MVC 的第一次親密接觸
常用开发工具介绍
Android应用开发 - 沈大海
Flex 4.5 action custom component development
Struts快速学习指南
一拍一产品背后的故事(React实战)
使用 Kong 與 GitOps 來管理您企業的 API 呼叫 @ 2024 台灣雲端大會
rebar erlang 2
YUIconf2010介绍
Spring 2.x 中文
Kissy design

Uliweb cheat sheet_0.1

  • 1. Uliweb Cheat Sheet 0.1 作者:limodou@gmail.com 整体介绍 说明:Uliweb 是一个 Python Web 开发框架 开发模式:MVT(Model, View, Template) 项目结构: project/ apps/ settings.ini app1/ templates/ xxx.html settings.ini views.py models.py … app.yaml gae_handler.py fcgi_handler.py wsgi_handler.py 项目主页: http://code.google.com/p/uliweb 安装 svn co http://uliweb.googlecode.com/svn/trunk/ uliweb python setup.py develop Hello,Uliweb - 第一个 Uliweb 程序 uliweb makeproject Project1 cd Project1 uliweb makeapp Hello uliweb runserver 在浏览器访问: http://localhost:8000 开发流程 功能开发:创建 App->编辑 views->设置 url|处理 Model| 处理 Form 配置开发:修改 app 的 settings|使用 dispatch View 基本内容 文件名:views.py, views_xx.py, views_yy.py def __begin__(): #进入 view 函数之前的处理 def __end__(): #执行 view 函数之后的处理 @expose(‘/’) def index(): return ‘Hello,world’ @expose(‘/user/<name>’) #expose 中可以定义参数 def user_view(name): #在 view 函数中要定义同名参数 from werkzeug import Response return Response(‘Hello, world’)#返回一个 Response Expose 格式 @expose(‘/user/<name>’) @expose(‘/users’ , default={‘pageno’:0})#可以传入缺省值 @expose(‘/users/<int:pageno>’)#匹配整数 @expose(‘/files/<path:file>’) #匹配/files/之后的内容(含/) @GET(URL) #只允许 GET 方式 @POST(URL) #只允许 POST 方式 命名 url @expose(‘/user/<name>’, name=’user_view’) #反向获取 url_for(’user_view’, name=’test’) View 的返回值 Response() #from werkzeug import Response ‘Hello’ {} #自动套用同名的模板 json(data) redirect(new_url) error(error_message) others #自动使用 str(others) 可以在 view 中和 template 中直接使用的变量 request #线程安全 response #线程安全 application #当前应用对象 settings #配置对象 json #json 数据 url_for #反向 url 获取 error #出错 redirect #重定向 ⊙也可以通过 from uliweb import xx 来导入上面内容 反向 url 获取(url_for) url_for(‘appname.views.view_func’, **kwargs) url_for(‘named_url’, **kwargs) url_for(view_func, **kwargs) 安装 uliweb.contrib.staticfiles 之后,可以使用: url_for_static(filename) #获得静态文件 url Template 语法 {{=var}} #escape html chars {{=func()}} #escape html chars {{python code}} {{<< htmlcode}} #unescape html chars {{if user=='admin':}} <p>Welcome</p> {{else:}} <a href="/login">Login</a> {{pass}} {{block content}}<div>default content</div>{{end}} {{embed var}} {{include “template.html”}} or {{include var}} {{extend “template.html”}} or {{extend var}} 安装 uliweb.contrib.template 之后,可以使用:
  • 2. {{use “template_plugin_name”}} {{link “js|css”}} settings.ini 语法 #coding=UTF-8 [GLOBAL] DEBUG = True INSTALLED_APPS = [ 'uliweb.contrib.staticfiles', ] MIDDLEWARE_CLASSES = [ 'uliweb.orm.middle_transaction.TransactionMiddle' ] TIME_ZONE = 'UTC' uliweb 命令行 uliweb 显示全部可用的命令(根据有效的 app 生成) uliweb runserver 启动开发服务器 uliweb develop 启动开发服务器,同时装入 develop app uliweb makeproject 创建一个项目 uliweb makeapp 创建一个 app uliweb makepkg 创建一个 python 的包目录 uliweb shell 进入 shell 环境 uliweb i18n 执行 i18n 的处理 uliweb extracturls 将所有 url 取出放入 urls.py uliweb exportstatic 将所有静态文件导出到指定目录 uliweb call 调用 app 下的命令 安装 uliweb.contrib.orm 后,可以使用: uliweb dbinit 执行 app 下的 dbinit.py 程序,进行初始化 uliweb dump dump 出数据库中的数 uliweb load 将 dump 的数据重新装回数据库 uliweb syncdb 自动创建表 uliweb sql 查看 create table 语句 uliewb reset 重新建表 安装 uliweb.contrib.auth 后可以执行: uliweb createsuperuser 创建超级用户 ORM-settings.ini 设置 [ORM] DEBUG_LOG = False AUTO_CREATE = True CONNECTION = 'sqlite://' CONNECTION 格式: #sqlite ‘sqlite:////absolute/path/to/database.txt’ ‘sqlite:///d:/absolute/path/to/database.txt’ ‘sqlite:///relative/path/to/database.txt’ ‘sqlite://’ # in-memory database ‘sqlite://:memory:’ # the same # postgresql 'postgres://scott:tiger@localhost/mydatabase' # mysql 'mysql://scott:tiger@localhost/mydatabase' # oracle 'oracle://scott:tiger@127.0.0.1:1521/sidname' # oracle via TNS name 'oracle://scott:tiger@tnsname' # mssql using ODBC datasource names. PyODBC is the default driver. 'mssql://mydsn' 'mssql://scott:tiger@mydsn' # firebird 'firebird://scott:tiger@localhost/sometest.gdm' ORM-Model 定义 from uliweb.orm import * class Requirement(Model): req_id = Field(CHAR, max_length=12,) year = Field(int, required=True) 可用字段(简便方式): StringProperty Field(str) #vchar CharProperty Field(CHAR) #char UnicodeProperty Field(Unicode)#vchar TextProperty Field(TEXT) #Text BlobProperty Field(BLOB) #Blob FileProperty Field(FILE) #vchar,保存文件名 IntegerProperty Field(int) #int FloatProperty Field(float) #float BooleanProperty Field(bool) #boolean DateTimeProperty Field(datetime)#datetime DateProperty Field(date) #date TimeProperty Field(time) #time DecimalProperty Field(DECIMAL)#numeric 关系定义: Reference SelfReference OneToOne ManyToMany 自定义表属性: class Note(Model): __tableame__ = 't_note'#表名 __table_args__ = dict(mysql_charset='utf8') @classmethod def OnInit(cls): Index('my_indx', cls.c.title, cls.c.owner, unique=True) Model 属性: .table #sqlalchemy 中的 Table 对象 .metadate #sqlalchemy 中的 metadata 对象 .c #等同于 model.table.c
  • 3. .properties #属性列表 ._manytomany #manytomany 属性 ORM-实例级操作 class User(Model): username = Field(CHAR, max_length=20) year = Field(int) 创建: user = User(username=’user’, year=20) user.save() 获取: user = User.get(1) user = User.get(User.c.id == 1) 删除: user.delete() 修改: user.username = ‘user1’ user.save() or user.update(**data) 其它方法: user.to_dict(*fields) ORM-表级操作 User.all() User.filter(User.c.year > 18) User.remove(condition) User.count(condition) ORM-结果集操作 直接返回单表结果集: User.all() User.filter() 通过关系返回结果集: class User(Model): username = Field(CHAR, max_length=20) year = Field(int) class Group(Model): name = Field(str, max_length=20) manager = Reference(User, collection_name=’m_groups’) users = ManyToMany(User,collection_name=’groups’) 以下方法返回结果集: user.m_groups #多表结果集 group.users #多表结果集 user.groups #单表结果集 单表结果集方法: all() #全部,返回结果集 filter() #过滤,返回结果集 order_by() #排序,返回结果集 limit() #限制,返回结果集 offset() #偏移,返回结果集 distinct() #不重复,返回结果集 返回结果: clear() #清除 count() #计数 one() #单条记录 values() #返回字段列表的[]结果 values_one() #返回字段列表的单条结果 多表结果集方法: all() #全部,返回结果集 filter() #过滤,返回结果集 order_by() #排序,返回结果集 limit() #限制,返回结果集 offset() #偏移,返回结果集 distinct() #不重复,返回结果集 返回结果: clear() #清除 count() #计数 one() #单条记录 values() #返回字段列表的[]结果 values_one() #返回字段列表的单条结果 has() #存在 Model-Settings 配置 在 settings.ini 中,如下: [MODELS] assignment = 'assignments.models.Assignment' 以后可以通过以下方式获得 Model: from uliweb.orm import get_model Assignment = get_model(‘assignment’) 同时可以在定义关系时,使用字符串来表示一个表。 Dispatch 主题 dispatch.call(application, 'startup_installed') dispatch.call(application, 'startup') dispatch.call(application, 'prepare_view_env', env) 安装完 uliweb.contrib.orm 后增加: dispatch.call(model, 'pre_save', instance, created, data, old_data) dispatch.call(model, 'post_save', instance, created, data, old_data) dispatch.call(model, 'pre_delete', instance) dispatch.call(model, 'post_delete', instance)