SlideShare ist ein Scribd-Unternehmen logo
1 von 35
一种多屏时代的通用 web 应用架构
赖勇浩 @ 珠三角技术沙龙
2013-5-19
自我介绍
●
game → webgame → web
●
珠三角技术沙龙组委、发起人之一
●
PyCon China 2011/2012 讲师
– Python 于 webgame 的应用
– 页游开发中的 Python 组件与模式
●
http://laiyonghao.com/
内容概述
●
Web 架构的变迁
●
实践经验分享
●
未来之路
Web 架构的变迁( 1 )
browser server
text/html
多屏时代有点不同。
Web 架构的变迁( 2 )
browser
serverwap browser
app
Web 架构的变迁( 2 )
●
问题:
– 返回什么?
Web 架构的变迁( 2 )
●
def request_wants_json():
●
best = request.accept_mimetypes 
●
.best_match(['application/json', 'text/html'])
●
return best == 'application/json' and 
●
request.accept_mimetypes[best] > 
●
request.accept_mimetypes['text/html']
Web 架构的变迁( 2 )
●
@app.route('/')
●
def show_items():
●
items = get_items_from_database()
●
if request_wants_json():
●
return jsonify(items=[x.to_json() for x in items])
●
return render_template('show_items.html',
items=items)
插播: Accept
插播: mimerender
●
mimerender = mimerender.FlaskMimeRender()
●
render_xml = lambda message: '<message>
%s</message>'%message
●
render_json = lambda **args: json.dumps(args)
●
render_html = lambda message: '<html><body>
%s</body></html>'%message
●
render_txt = lambda message: message
插播: mimerender
●
@app.route('/')
●
@app.route('/<name>')
●
@mimerender(
●
default = 'html',
●
html = render_html,
●
xml = render_xml,
●
json = render_json,
●
txt = render_txt
●
)
●
def greet(name='world'):
●
return {'message':
'Hello, ' + name + '!'}
●
if __name__ ==
"__main__":
●
app.run(port=8080)
插播: mimerender
●
How to get it
– mimerender is in PyPI, so it's as easy as doing:
– $ pip install mimerender
Web 架构的变迁( 2 )
browser
server
text/html
wap browser
app
text/vnd.wap.wml
application/json
Web 架构的变迁( 3 )
●
如果可以通过短信( SMS ……)使用业务
Web 架构的变迁( 3 )
browser
adapter
text/html
wap browser
app
text/vnd.wap.wml
application/json
adapter
adapter
server
adapterSMS
application/json
Web 架构的变迁( 3 )
browser
adapter
text/html
wap browser
app
text/vnd.wap.wml
application/json
adapter
adapter
server
adapterSMS
application/json
?
Web 架构的变迁( 3 )
●
业务与展现分享
– server 专注业务实现,只需要提供 http api ,无须理
会数据展现形式;
– adapter 的业务简单,只需要维护会话,并对请求 / 响
应进行转换;
●
易于分工
– 内部可以分小组
– 甚至外包(解决了我团队不熟悉短信中心协议的问题)
●
易于扩展
– 支持更多设备(如自助终端、语音电话)
Web 架构的变迁( 3 )
●
安全:对数据进行签名
– client-id 、 client-key
– sha1
– 让 Date header 必填来确保每次请救不同
实践经验分享
●
Flask-RESTful
– https://github.com/twilio/flask-restful
Flask-RESTful: Argument Parsing
●
parser = reqparse.RequestParser()
●
parser.add_argument('rate', type=int, help='Rate to
charge for this resource')
●
args = parser.parse_args()
●
支持必填项、多值项、重命名
●
可从 post body 、 query
string 、 headers 、 cookies 、 file uploads 中读取
Flask-RESTful: Output Fields
●
resource_fields = {
●
'name': fields.String,
●
'address': fields.String,
●
'date_updated': fields.DateTime,
●
}
●
class Todo(Resource):
●
@marshal_with(resource_fields)
●
def get(self, **kwargs):
●
return db_get_todo() # Some function that queries
the db
Flask-RESTful: Output Fields
●
Renaming Attributes
●
Default Values
●
Custom Fields & Multiple Values
●
Url Field
●
Complex Structures
●
List Field
●
Nested Field
Flask-RESTful: Resource Method
Decorators
●
def authenticate(func):
●
@wraps(func)
●
def wrapper(*args, **kwargs):
●
...
●
class Resource(restful.Resource):
●
method_decorators = [authenticate] # applies to all
inherited resources
测试
●
一般情况下使用 curl 足矣
– $ curl http://localhost:5000/todos/todo3
– {"task": "profit!"}
chtest
●
$ chtest --help
●
usage: chtest [-h] [--config-file CONFIG_FILE] --path
PATH [--method METHOD]
●
[--arg ARG] [--header HEADER] [--ensure-status
ENSURE_STATUS]
●
[--ensure-header ENSURE_HEADER]
●
[--ensure-content ENSURE_CONTENT] [--print-
header PRINT_HEADER]
●
[--print-json-path PRINT_JSON_PATH]
requests
●
chtest is requests powered
●
Requests: HTTP for Humans
– >>> r = requests.get('https://api.github.com/user',
auth=('user', 'pass'))
– >>> r.status_code
– 200
– >>> r.headers['content-type']
– 'application/json; charset=utf8'
– >>> r.text
– u'{"type":"User"...'
– >>> r.json()
未来之路
●
http-based VS tcp-based
●
Behavior-Driven Development
Web 架构的变迁( 3 )
browser
adapter
text/html
wap browser
app
text/vnd.wap.wml
application/json
adapter
adapter
server
adapterSMS
RPC ??
RPC 优劣
●
优势
– 减少连接数
– 更小的数据包
– 乱序返回
– 握手后的数据不需要签名( SSL/TLS )
●
劣势
– 不能利用 HTTP 的基础设施
– 需要学习好多新东西
lettuce.it
●
Feature: Manipulate strings
●
In order to have some fun
●
As a programming beginner
●
I want to manipulate strings
●
Scenario: Uppercased strings
●
Given I have the string "lettuce leaves"
●
When I put it in upper case
●
Then I see the string is "LETTUCE LEAVES"
lettuce.it
●
>>> @step('I have the string "(.*)"')
●
... def have_the_string(step, string):
●
... world.string = string
●
>>> @step('I put it in upper case')
●
... def put_it_in_upper(step):
●
... world.string = world.string.upper()
●
>>> @step('I see the string is "(.*)"')
●
... def see_the_string_is(step, expected):
●
... assert world.string == expected, 
●
... "Got %s" % world.string
lettuce.it
●
from lettuce import step
●
from nose.tools import assert_equals
●
@step('some step with "(.*)"'):
●
def some_step(step, from):
●
assert_equals(from, 'expectation')
End.
Thanks.
@laiyonghao
额外赠送: flask-pypi-proxy
您值得拥有。

Weitere ähnliche Inhalte

Was ist angesagt?

openstack源码分析(1)
openstack源码分析(1)openstack源码分析(1)
openstack源码分析(1)
cannium
 
Full-Stack JavaScript with Node.js
Full-Stack JavaScript with Node.jsFull-Stack JavaScript with Node.js
Full-Stack JavaScript with Node.js
Michael Lehmann
 

Was ist angesagt? (18)

Rubyslava + PyVo #48
Rubyslava + PyVo #48Rubyslava + PyVo #48
Rubyslava + PyVo #48
 
OpenCms Days 2014 - Using the SOLR collector
OpenCms Days 2014 - Using the SOLR collectorOpenCms Days 2014 - Using the SOLR collector
OpenCms Days 2014 - Using the SOLR collector
 
Config BuildConfig
Config BuildConfigConfig BuildConfig
Config BuildConfig
 
OpenCms Days 2012 - OpenCms 8.5: Using Apache Solr to retrieve content
OpenCms Days 2012 - OpenCms 8.5: Using Apache Solr to retrieve contentOpenCms Days 2012 - OpenCms 8.5: Using Apache Solr to retrieve content
OpenCms Days 2012 - OpenCms 8.5: Using Apache Solr to retrieve content
 
MongoDB & PHP
MongoDB & PHPMongoDB & PHP
MongoDB & PHP
 
"Metrics: Where and How", Vsevolod Polyakov
"Metrics: Where and How", Vsevolod Polyakov"Metrics: Where and How", Vsevolod Polyakov
"Metrics: Where and How", Vsevolod Polyakov
 
PgconfSV compression
PgconfSV compressionPgconfSV compression
PgconfSV compression
 
Using Geoscript Groovy
Using Geoscript GroovyUsing Geoscript Groovy
Using Geoscript Groovy
 
Hujs 总结
Hujs 总结Hujs 总结
Hujs 总结
 
Do something in 5 with apps scripts number 6 - fusion crossfilter
Do something in 5 with apps scripts number 6 - fusion crossfilterDo something in 5 with apps scripts number 6 - fusion crossfilter
Do something in 5 with apps scripts number 6 - fusion crossfilter
 
Introducere in web
Introducere in webIntroducere in web
Introducere in web
 
Flask intro - ROSEdu web workshops
Flask intro - ROSEdu web workshopsFlask intro - ROSEdu web workshops
Flask intro - ROSEdu web workshops
 
openstack源码分析(1)
openstack源码分析(1)openstack源码分析(1)
openstack源码分析(1)
 
N hidden gems in forge (as of may '17)
N hidden gems in forge (as of may '17)N hidden gems in forge (as of may '17)
N hidden gems in forge (as of may '17)
 
Ceph BlueStore - новый тип хранилища в Ceph / Максим Воронцов, (Redsys)
Ceph BlueStore - новый тип хранилища в Ceph / Максим Воронцов, (Redsys)Ceph BlueStore - новый тип хранилища в Ceph / Максим Воронцов, (Redsys)
Ceph BlueStore - новый тип хранилища в Ceph / Максим Воронцов, (Redsys)
 
Import
ImportImport
Import
 
MongoDB Munich 2012: MongoDB for official documents in Bavaria
MongoDB Munich 2012: MongoDB for official documents in BavariaMongoDB Munich 2012: MongoDB for official documents in Bavaria
MongoDB Munich 2012: MongoDB for official documents in Bavaria
 
Full-Stack JavaScript with Node.js
Full-Stack JavaScript with Node.jsFull-Stack JavaScript with Node.js
Full-Stack JavaScript with Node.js
 

Andere mochten auch (10)

如何做好沙龙演讲
如何做好沙龙演讲如何做好沙龙演讲
如何做好沙龙演讲
 
Tp web
Tp webTp web
Tp web
 
为什么 rust-lang 吸引我?
为什么 rust-lang 吸引我?为什么 rust-lang 吸引我?
为什么 rust-lang 吸引我?
 
La communication 3 D
La communication 3 DLa communication 3 D
La communication 3 D
 
To My Friends
To My FriendsTo My Friends
To My Friends
 
游戏地图自动生成
游戏地图自动生成游戏地图自动生成
游戏地图自动生成
 
论 Python 与设计模式。
论 Python 与设计模式。论 Python 与设计模式。
论 Python 与设计模式。
 
Enjeux publicitaires
Enjeux publicitairesEnjeux publicitaires
Enjeux publicitaires
 
Audit de la communication du conseil général de la gironde
Audit de la communication du conseil général de la girondeAudit de la communication du conseil général de la gironde
Audit de la communication du conseil général de la gironde
 
Digital Bank, May 2014
Digital Bank, May 2014Digital Bank, May 2014
Digital Bank, May 2014
 

Ähnlich wie 一种多屏时代的通用 web 应用架构

Deployments with rails
Deployments with railsDeployments with rails
Deployments with rails
Gourav Tiwari
 

Ähnlich wie 一种多屏时代的通用 web 应用架构 (20)

Grails 101
Grails 101Grails 101
Grails 101
 
Andriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tipsAndriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tips
 
202107 - Orion introduction - COSCUP
202107 - Orion introduction - COSCUP202107 - Orion introduction - COSCUP
202107 - Orion introduction - COSCUP
 
Dragoncraft Architectural Overview
Dragoncraft Architectural OverviewDragoncraft Architectural Overview
Dragoncraft Architectural Overview
 
Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)
 
Cli jbug
Cli jbugCli jbug
Cli jbug
 
AS7 and CLI
AS7 and CLIAS7 and CLI
AS7 and CLI
 
Autolab Workshop
Autolab WorkshopAutolab Workshop
Autolab Workshop
 
FOSDEM 2015: gdb tips and tricks for MySQL DBAs
FOSDEM 2015: gdb tips and tricks for MySQL DBAsFOSDEM 2015: gdb tips and tricks for MySQL DBAs
FOSDEM 2015: gdb tips and tricks for MySQL DBAs
 
Clean code and refactoring
Clean code and refactoringClean code and refactoring
Clean code and refactoring
 
Bangpypers april-meetup-2012
Bangpypers april-meetup-2012Bangpypers april-meetup-2012
Bangpypers april-meetup-2012
 
Fast federated SQL with Apache Calcite
Fast federated SQL with Apache CalciteFast federated SQL with Apache Calcite
Fast federated SQL with Apache Calcite
 
Ci for all
Ci for allCi for all
Ci for all
 
Deployments with rails
Deployments with railsDeployments with rails
Deployments with rails
 
Backbone 4.0
Backbone 4.0Backbone 4.0
Backbone 4.0
 
Go Is Your Next Language — Sergii Shapoval
Go Is Your Next Language — Sergii ShapovalGo Is Your Next Language — Sergii Shapoval
Go Is Your Next Language — Sergii Shapoval
 
Php 5.6 From the Inside Out
Php 5.6 From the Inside OutPhp 5.6 From the Inside Out
Php 5.6 From the Inside Out
 
Sprint 17
Sprint 17Sprint 17
Sprint 17
 
Dart the Better JavaScript
Dart the Better JavaScriptDart the Better JavaScript
Dart the Better JavaScript
 
JS Essence
JS EssenceJS Essence
JS Essence
 

Mehr von 勇浩 赖

Behavior+tree+ai lite
Behavior+tree+ai liteBehavior+tree+ai lite
Behavior+tree+ai lite
勇浩 赖
 
敏捷网游架构与性能的新玩法
敏捷网游架构与性能的新玩法敏捷网游架构与性能的新玩法
敏捷网游架构与性能的新玩法
勇浩 赖
 
03 -黄朝兴--腾讯游戏
03 -黄朝兴--腾讯游戏03 -黄朝兴--腾讯游戏
03 -黄朝兴--腾讯游戏
勇浩 赖
 
06 -甄焱琨--知识转化为资源
06 -甄焱琨--知识转化为资源06 -甄焱琨--知识转化为资源
06 -甄焱琨--知识转化为资源
勇浩 赖
 
Techparty story
Techparty storyTechparty story
Techparty story
勇浩 赖
 

Mehr von 勇浩 赖 (20)

2012,我的技术之选
2012,我的技术之选2012,我的技术之选
2012,我的技术之选
 
页游开发中的 Python 组件与模式
页游开发中的 Python 组件与模式页游开发中的 Python 组件与模式
页游开发中的 Python 组件与模式
 
Scala
ScalaScala
Scala
 
珠三角技术沙龙广州场
珠三角技术沙龙广州场珠三角技术沙龙广州场
珠三角技术沙龙广州场
 
Python 于 webgame 的应用
Python 于 webgame 的应用Python 于 webgame 的应用
Python 于 webgame 的应用
 
Behavior+tree+ai lite
Behavior+tree+ai liteBehavior+tree+ai lite
Behavior+tree+ai lite
 
敏捷网游架构与性能的新玩法
敏捷网游架构与性能的新玩法敏捷网游架构与性能的新玩法
敏捷网游架构与性能的新玩法
 
先用再学 - 借助 Xna 快速开发游戏原型
先用再学  - 借助 Xna 快速开发游戏原型先用再学  - 借助 Xna 快速开发游戏原型
先用再学 - 借助 Xna 快速开发游戏原型
 
关于Bitworld的一些话题222
关于Bitworld的一些话题222关于Bitworld的一些话题222
关于Bitworld的一些话题222
 
Stekin
StekinStekin
Stekin
 
03 -黄朝兴--腾讯游戏
03 -黄朝兴--腾讯游戏03 -黄朝兴--腾讯游戏
03 -黄朝兴--腾讯游戏
 
abu.rpc intro
abu.rpc introabu.rpc intro
abu.rpc intro
 
06 -甄焱琨--知识转化为资源
06 -甄焱琨--知识转化为资源06 -甄焱琨--知识转化为资源
06 -甄焱琨--知识转化为资源
 
07 -林伟铃--成长中的36氪
07 -林伟铃--成长中的36氪07 -林伟铃--成长中的36氪
07 -林伟铃--成长中的36氪
 
01 -阿朱--简单事情夯实做
01 -阿朱--简单事情夯实做01 -阿朱--简单事情夯实做
01 -阿朱--简单事情夯实做
 
Python 温故
Python 温故Python 温故
Python 温故
 
虚拟世界是怎么炼成的(图片版)
虚拟世界是怎么炼成的(图片版)虚拟世界是怎么炼成的(图片版)
虚拟世界是怎么炼成的(图片版)
 
Techparty story
Techparty storyTechparty story
Techparty story
 
2010,我的技术之选
2010,我的技术之选2010,我的技术之选
2010,我的技术之选
 
python-message-0.1.0
python-message-0.1.0python-message-0.1.0
python-message-0.1.0
 

Kürzlich hochgeladen

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 

Kürzlich hochgeladen (20)

CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 

一种多屏时代的通用 web 应用架构