SlideShare ist ein Scribd-Unternehmen logo
1 von 20
Downloaden Sie, um offline zu lesen
⽤用Tornado开发RESTful
                  API运⽤用
                 ⻜飞⻰龙⾮非⻰龙 (http://feilong.me)
                        2012/10/20




12年10月14⽇日星期⽇日
议程

                 • RESTful API简介
                 • ⽤用Tornado开发RESTful API应⽤用
                 • D3status demo APP


12年10月14⽇日星期⽇日
12年10月14⽇日星期⽇日
Service

         Resource   Service   API   Clients




12年10月14⽇日星期⽇日
RESTful API

                           OAuth




                       HTTPS GET/POST

                 App                    Platform
                         JSON/JSONP




12年10月14⽇日星期⽇日
RESTful and HTTP Verbs


            Level 0   GET   POST   PUT   DELETE   PATCH

            Level 1   GET   POST   PUT   DELETE   PATCH

            Level 2   GET   POST   PUT   DELETE   PATCH




12年10月14⽇日星期⽇日
RESTful in Tornado
                 class RequestHandler(object):
                     """Subclass this class and define get() or post() to make a handler.

                     If you want to support more methods than the standard GET/HEAD/POST, you
                     should override the class variable SUPPORTED_METHODS in your
                     RequestHandler class.
                     """
                     SUPPORTED_METHODS = ("GET", "HEAD", "POST", "DELETE", "PATCH", "PUT",
                                           "OPTIONS")

                    def head(self, *args, **kwargs):
                        raise HTTPError(405)

                    def get(self, *args, **kwargs):
                        raise HTTPError(405)

                    def post(self, *args, **kwargs):
                        raise HTTPError(405)

                    def delete(self, *args, **kwargs):
                        raise HTTPError(405)

                    def patch(self, *args, **kwargs):
                        raise HTTPError(405)

                    def put(self, *args, **kwargs):
                        raise HTTPError(405)

                    def options(self, *args, **kwargs):
                        raise HTTPError(405)

12年10月14⽇日星期⽇日
JSON & JSONP
                 class APIHandler(BaseHandler):

                     def finish(self, chunk=None, notification=None):
                         if chunk is None:
                             chunk = {}

                         if isinstance(chunk, dict):
                             chunk = {"meta": {"code": 200}, "response": chunk}

                             if notification:
                                 chunk["notification"] = {"message": notification}

                         callback = escape.utf8(self.get_argument("callback", None))
                         if callback:
                             self.set_header("Content-Type", "application/x-javascript")

                             if isinstance(chunk, dict):
                                 chunk = escape.json_encode(chunk)

                             self._write_buffer = [callback, "(", chunk, ")"] if chunk else []
                             super(APIHandler, self).finish()
                         else:
                             self.set_header("Content-Type", "application/json; charset=UTF-8")
                             super(APIHandler, self).finish(chunk)




12年10月14⽇日星期⽇日
Exception
                 def write_error(self, status_code, **kwargs):
                     """Override to implement custom error pages."""
                     debug = self.settings.get("debug", False)
                     try:
                          exc_info = kwargs.pop('exc_info')
                          e = exc_info[1]

                        if isinstance(e, exceptions.HTTPAPIError):
                            pass
                        elif isinstance(e, HTTPError):
                            e = exceptions.HTTPAPIError(e.status_code)
                        else:
                            e = exceptions.HTTPAPIError(500)

                         exception = "".join([ln for ln in traceback.format_exception(*exc_info)])

                        if status_code == 500 and not debug:
                            self._send_error_email(exception)

                        if debug:
                            e.response["exception"] = exception

                        self.clear()
                        self.set_status(200) # always return 200 OK for API errors
                        self.set_header("Content-Type", "application/json; charset=UTF-8")
                        self.finish(str(e))
                    except Exception:
                        logging.error(traceback.format_exc())
                        return super(APIHandler, self).write_error(status_code, **kwargs)
12年10月14⽇日星期⽇日
Exception
                 class HTTPAPIError(HTTPError):
                     """API error handling exception

                     API server always returns formatted JSON to client even there is
                     an internal server error.
                     """
                     def __init__(self, status_code=400, error_detail="", error_type="",
                                  notification="", response="", log_message=None, *args):

                         super(HTTPAPIError, self).__init__(int(status_code), log_message, *args)

                         self.error_type = error_type if error_type else 
                             _error_types.get(self.status_code, "unknow_error")
                         self.error_detail = error_detail
                         self.notification = {"message": notification} if notification else {}
                         self.response = response if response else {}

                     def __str__(self):
                         err = {"meta": {"code": self.status_code, "errorType": self.error_type}}
                         self._set_err(err, ["notification", "response"])

                         if self.error_detail:
                             err["meta"]["errorDetail"] = self.error_detail

                         return escape.json_encode(err)



12年10月14⽇日星期⽇日
12年10月14⽇日星期⽇日
12年10月14⽇日星期⽇日
12年10月14⽇日星期⽇日
12年10月14⽇日星期⽇日
⺴⽹网⻚页抓取

                 def update_server_status():
                     url = options.d3_server_status_url
                     req = HTTPRequest(url=url)

                     client = HTTPClient()
                     response = client.fetch(req)
                     if response.code == 200:
                         status = _parse_server_status(response.body)




12年10月14⽇日星期⽇日
⺴⽹网⻚页解析
                 def _parse_server_status(body):
                     status = {}

                     q = pq(etree.fromstring(body))
                     boxes = q(".box") # category box
                     for box in boxes:
                         box_q = pq(etree.fromstring(etree.tostring(box)))
                         category = box_q(".category")[0].text.strip()
                         status[category] = {}
                         servers = box_q(".server")
                         for server in servers:
                             server_q = pq(etree.fromstring(etree.tostring(server)))
                             server_name = server_q(".server-name")[0].text.strip().replace(" ", "")
                             if server_name:
                                 status_icon = server_q(".status-icon")[0]
                                 class_ = status_icon.get("class")
                                 if class_:
                                     st = 0
                                     if "up" in class_:
                                         st = 1
                                     status[category][server_name] = st

                     return status




12年10月14⽇日星期⽇日
@task
                                        任务队列
        def status_notification_task(changed_status):
            status_notifciation(changed_status)



        def status_notifciation(changed_status):
            notifications = {}
            for category, services in changed_status.iteritems():
                for name, st in services.iteritems():
                    # just push notification about game server now
                    if name == "GameServer":
                        notifications[category] = st

            for category, st in notifications.iteritems():
                status = "Available" if st else "Unavailable"

                 offset = 0
                 limit = 200
                 while True:
                     subscribers = load_model("subscribers").get_subscribers(limit, offset)
                     if not subscribers:
                         break

                     for subscribe in subscribers:
                         if category in subscribe.categorys:
                             alert = _trans_alert("Diablo3 %s server status has changed to %s",
                                                   category, status, subscribe.locale)
                             apns_tasks.apns_push_task.delay(subscribe.token, {},
                                                              alert=alert, badge=1,
                                                              sound="default")
                     offset += len(subscribers)

12年10月14⽇日星期⽇日
其它

                 • Apple push notification
                 • i18n
                 • crontab


12年10月14⽇日星期⽇日
相关资源
                 • https://github.com/felinx/d3status
                 • http://www.tornadoweb.org
                 • http://www.tornadoweb.cn
                 • http://tornado.poweredsites.org
                 • http://tornadogists.org
                 • http://en.wikipedia.org/wiki/
                   Representational_state_transfer
12年10月14⽇日星期⽇日
Q&A

                    @⻜飞⻰龙⾮非⻰龙

                 http://feilong.me/




12年10月14⽇日星期⽇日

Weitere ähnliche Inhalte

Was ist angesagt?

Webrtc mojo
Webrtc mojoWebrtc mojo
Webrtc mojobpmedley
 
Tornado web
Tornado webTornado web
Tornado webkurtiss
 
Tornado - different Web programming
Tornado - different Web programmingTornado - different Web programming
Tornado - different Web programmingDima Malenko
 
Perl web frameworks
Perl web frameworksPerl web frameworks
Perl web frameworksdiego_k
 
Python, async web frameworks, and MongoDB
Python, async web frameworks, and MongoDBPython, async web frameworks, and MongoDB
Python, async web frameworks, and MongoDBemptysquare
 
Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)Kris Wallsmith
 
Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...
Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...
Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...King Foo
 
Nginx + Tornado = 17k req/s
Nginx + Tornado = 17k req/sNginx + Tornado = 17k req/s
Nginx + Tornado = 17k req/smoret1979
 
An Introduction to Tornado
An Introduction to TornadoAn Introduction to Tornado
An Introduction to TornadoGavin Roy
 
News of the Symfony2 World
News of the Symfony2 WorldNews of the Symfony2 World
News of the Symfony2 WorldFabien Potencier
 
Building Web Apps with Express
Building Web Apps with ExpressBuilding Web Apps with Express
Building Web Apps with ExpressAaron Stannard
 
Introducing Assetic: Asset Management for PHP 5.3
Introducing Assetic: Asset Management for PHP 5.3Introducing Assetic: Asset Management for PHP 5.3
Introducing Assetic: Asset Management for PHP 5.3Kris Wallsmith
 
Keeping it small: Getting to know the Slim micro framework
Keeping it small: Getting to know the Slim micro frameworkKeeping it small: Getting to know the Slim micro framework
Keeping it small: Getting to know the Slim micro frameworkJeremy Kendall
 
Tornado Web Server Internals
Tornado Web Server InternalsTornado Web Server Internals
Tornado Web Server InternalsPraveen Gollakota
 
Phl mongo-philly-tornado-2011
Phl mongo-philly-tornado-2011Phl mongo-philly-tornado-2011
Phl mongo-philly-tornado-2011hangxin1940
 
Trading with opensource tools, two years later
Trading with opensource tools, two years laterTrading with opensource tools, two years later
Trading with opensource tools, two years laterclkao
 
HTTP Caching and PHP
HTTP Caching and PHPHTTP Caching and PHP
HTTP Caching and PHPDavid de Boer
 

Was ist angesagt? (20)

Webrtc mojo
Webrtc mojoWebrtc mojo
Webrtc mojo
 
Symfony 2.0 on PHP 5.3
Symfony 2.0 on PHP 5.3Symfony 2.0 on PHP 5.3
Symfony 2.0 on PHP 5.3
 
Tornado web
Tornado webTornado web
Tornado web
 
Tornado - different Web programming
Tornado - different Web programmingTornado - different Web programming
Tornado - different Web programming
 
Perl web frameworks
Perl web frameworksPerl web frameworks
Perl web frameworks
 
Python, async web frameworks, and MongoDB
Python, async web frameworks, and MongoDBPython, async web frameworks, and MongoDB
Python, async web frameworks, and MongoDB
 
Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)
 
Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...
Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...
Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...
 
Mojo as a_client
Mojo as a_clientMojo as a_client
Mojo as a_client
 
Nginx + Tornado = 17k req/s
Nginx + Tornado = 17k req/sNginx + Tornado = 17k req/s
Nginx + Tornado = 17k req/s
 
An Introduction to Tornado
An Introduction to TornadoAn Introduction to Tornado
An Introduction to Tornado
 
News of the Symfony2 World
News of the Symfony2 WorldNews of the Symfony2 World
News of the Symfony2 World
 
Building Web Apps with Express
Building Web Apps with ExpressBuilding Web Apps with Express
Building Web Apps with Express
 
Tornadoweb
TornadowebTornadoweb
Tornadoweb
 
Introducing Assetic: Asset Management for PHP 5.3
Introducing Assetic: Asset Management for PHP 5.3Introducing Assetic: Asset Management for PHP 5.3
Introducing Assetic: Asset Management for PHP 5.3
 
Keeping it small: Getting to know the Slim micro framework
Keeping it small: Getting to know the Slim micro frameworkKeeping it small: Getting to know the Slim micro framework
Keeping it small: Getting to know the Slim micro framework
 
Tornado Web Server Internals
Tornado Web Server InternalsTornado Web Server Internals
Tornado Web Server Internals
 
Phl mongo-philly-tornado-2011
Phl mongo-philly-tornado-2011Phl mongo-philly-tornado-2011
Phl mongo-philly-tornado-2011
 
Trading with opensource tools, two years later
Trading with opensource tools, two years laterTrading with opensource tools, two years later
Trading with opensource tools, two years later
 
HTTP Caching and PHP
HTTP Caching and PHPHTTP Caching and PHP
HTTP Caching and PHP
 

Ähnlich wie 用Tornado开发RESTful API运用

Python magicmethods
Python magicmethodsPython magicmethods
Python magicmethodsdreampuf
 
Tools for Making Machine Learning more Reactive
Tools for Making Machine Learning more ReactiveTools for Making Machine Learning more Reactive
Tools for Making Machine Learning more ReactiveJeff Smith
 
Pruebas unitarias con django
Pruebas unitarias con djangoPruebas unitarias con django
Pruebas unitarias con djangoTomás Henríquez
 
PhpUnit - The most unknown Parts
PhpUnit - The most unknown PartsPhpUnit - The most unknown Parts
PhpUnit - The most unknown PartsBastian Feder
 
Flask patterns
Flask patternsFlask patterns
Flask patternsit-people
 
The Rule of 10,000 Spark Jobs: Learning From Exceptions and Serializing Your ...
The Rule of 10,000 Spark Jobs: Learning From Exceptions and Serializing Your ...The Rule of 10,000 Spark Jobs: Learning From Exceptions and Serializing Your ...
The Rule of 10,000 Spark Jobs: Learning From Exceptions and Serializing Your ...Databricks
 
The Rule of 10,000 Spark Jobs - Learning from Exceptions and Serializing Your...
The Rule of 10,000 Spark Jobs - Learning from Exceptions and Serializing Your...The Rule of 10,000 Spark Jobs - Learning from Exceptions and Serializing Your...
The Rule of 10,000 Spark Jobs - Learning from Exceptions and Serializing Your...Matthew Tovbin
 
Alexey Tsoy Meta Programming in C++ 16.11.17
Alexey Tsoy Meta Programming in C++ 16.11.17Alexey Tsoy Meta Programming in C++ 16.11.17
Alexey Tsoy Meta Programming in C++ 16.11.17LogeekNightUkraine
 
Jython: Python para la plataforma Java (EL2009)
Jython: Python para la plataforma Java (EL2009)Jython: Python para la plataforma Java (EL2009)
Jython: Python para la plataforma Java (EL2009)Leonardo Soto
 
Web осень 2012 лекция 6
Web осень 2012 лекция 6Web осень 2012 лекция 6
Web осень 2012 лекция 6Technopark
 
Web注入+http漏洞等描述
Web注入+http漏洞等描述Web注入+http漏洞等描述
Web注入+http漏洞等描述fangjiafu
 
Web весна 2013 лекция 6
Web весна 2013 лекция 6Web весна 2013 лекция 6
Web весна 2013 лекция 6Technopark
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on AndroidSven Haiges
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretssmueller_sandsmedia
 
Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Elena Kolevska
 
Jython: Python para la plataforma Java (JRSL 09)
Jython: Python para la plataforma Java (JRSL 09)Jython: Python para la plataforma Java (JRSL 09)
Jython: Python para la plataforma Java (JRSL 09)Leonardo Soto
 
Testing My Patience
Testing My PatienceTesting My Patience
Testing My PatienceAdam Lowry
 
And the Greatest of These Is ... Rack Support
And the Greatest of These Is ... Rack SupportAnd the Greatest of These Is ... Rack Support
And the Greatest of These Is ... Rack SupportBen Scofield
 

Ähnlich wie 用Tornado开发RESTful API运用 (20)

Python magicmethods
Python magicmethodsPython magicmethods
Python magicmethods
 
Tools for Making Machine Learning more Reactive
Tools for Making Machine Learning more ReactiveTools for Making Machine Learning more Reactive
Tools for Making Machine Learning more Reactive
 
Pruebas unitarias con django
Pruebas unitarias con djangoPruebas unitarias con django
Pruebas unitarias con django
 
PhpUnit - The most unknown Parts
PhpUnit - The most unknown PartsPhpUnit - The most unknown Parts
PhpUnit - The most unknown Parts
 
Flask patterns
Flask patternsFlask patterns
Flask patterns
 
The Rule of 10,000 Spark Jobs: Learning From Exceptions and Serializing Your ...
The Rule of 10,000 Spark Jobs: Learning From Exceptions and Serializing Your ...The Rule of 10,000 Spark Jobs: Learning From Exceptions and Serializing Your ...
The Rule of 10,000 Spark Jobs: Learning From Exceptions and Serializing Your ...
 
The Rule of 10,000 Spark Jobs - Learning from Exceptions and Serializing Your...
The Rule of 10,000 Spark Jobs - Learning from Exceptions and Serializing Your...The Rule of 10,000 Spark Jobs - Learning from Exceptions and Serializing Your...
The Rule of 10,000 Spark Jobs - Learning from Exceptions and Serializing Your...
 
Alexey Tsoy Meta Programming in C++ 16.11.17
Alexey Tsoy Meta Programming in C++ 16.11.17Alexey Tsoy Meta Programming in C++ 16.11.17
Alexey Tsoy Meta Programming in C++ 16.11.17
 
Jython: Python para la plataforma Java (EL2009)
Jython: Python para la plataforma Java (EL2009)Jython: Python para la plataforma Java (EL2009)
Jython: Python para la plataforma Java (EL2009)
 
Web осень 2012 лекция 6
Web осень 2012 лекция 6Web осень 2012 лекция 6
Web осень 2012 лекция 6
 
Web注入+http漏洞等描述
Web注入+http漏洞等描述Web注入+http漏洞等描述
Web注入+http漏洞等描述
 
Web весна 2013 лекция 6
Web весна 2013 лекция 6Web весна 2013 лекция 6
Web весна 2013 лекция 6
 
SDC - Einführung in Scala
SDC - Einführung in ScalaSDC - Einführung in Scala
SDC - Einführung in Scala
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on Android
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secrets
 
Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5
 
Nantes Jug - Java 7
Nantes Jug - Java 7Nantes Jug - Java 7
Nantes Jug - Java 7
 
Jython: Python para la plataforma Java (JRSL 09)
Jython: Python para la plataforma Java (JRSL 09)Jython: Python para la plataforma Java (JRSL 09)
Jython: Python para la plataforma Java (JRSL 09)
 
Testing My Patience
Testing My PatienceTesting My Patience
Testing My Patience
 
And the Greatest of These Is ... Rack Support
And the Greatest of These Is ... Rack SupportAnd the Greatest of These Is ... Rack Support
And the Greatest of These Is ... Rack Support
 

Kürzlich hochgeladen

How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 

Kürzlich hochgeladen (20)

How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 

用Tornado开发RESTful API运用

  • 1. ⽤用Tornado开发RESTful API运⽤用 ⻜飞⻰龙⾮非⻰龙 (http://feilong.me) 2012/10/20 12年10月14⽇日星期⽇日
  • 2. 议程 • RESTful API简介 • ⽤用Tornado开发RESTful API应⽤用 • D3status demo APP 12年10月14⽇日星期⽇日
  • 4. Service Resource Service API Clients 12年10月14⽇日星期⽇日
  • 5. RESTful API OAuth HTTPS GET/POST App Platform JSON/JSONP 12年10月14⽇日星期⽇日
  • 6. RESTful and HTTP Verbs Level 0 GET POST PUT DELETE PATCH Level 1 GET POST PUT DELETE PATCH Level 2 GET POST PUT DELETE PATCH 12年10月14⽇日星期⽇日
  • 7. RESTful in Tornado class RequestHandler(object): """Subclass this class and define get() or post() to make a handler. If you want to support more methods than the standard GET/HEAD/POST, you should override the class variable SUPPORTED_METHODS in your RequestHandler class. """ SUPPORTED_METHODS = ("GET", "HEAD", "POST", "DELETE", "PATCH", "PUT", "OPTIONS") def head(self, *args, **kwargs): raise HTTPError(405) def get(self, *args, **kwargs): raise HTTPError(405) def post(self, *args, **kwargs): raise HTTPError(405) def delete(self, *args, **kwargs): raise HTTPError(405) def patch(self, *args, **kwargs): raise HTTPError(405) def put(self, *args, **kwargs): raise HTTPError(405) def options(self, *args, **kwargs): raise HTTPError(405) 12年10月14⽇日星期⽇日
  • 8. JSON & JSONP class APIHandler(BaseHandler): def finish(self, chunk=None, notification=None): if chunk is None: chunk = {} if isinstance(chunk, dict): chunk = {"meta": {"code": 200}, "response": chunk} if notification: chunk["notification"] = {"message": notification} callback = escape.utf8(self.get_argument("callback", None)) if callback: self.set_header("Content-Type", "application/x-javascript") if isinstance(chunk, dict): chunk = escape.json_encode(chunk) self._write_buffer = [callback, "(", chunk, ")"] if chunk else [] super(APIHandler, self).finish() else: self.set_header("Content-Type", "application/json; charset=UTF-8") super(APIHandler, self).finish(chunk) 12年10月14⽇日星期⽇日
  • 9. Exception def write_error(self, status_code, **kwargs): """Override to implement custom error pages.""" debug = self.settings.get("debug", False) try: exc_info = kwargs.pop('exc_info') e = exc_info[1] if isinstance(e, exceptions.HTTPAPIError): pass elif isinstance(e, HTTPError): e = exceptions.HTTPAPIError(e.status_code) else: e = exceptions.HTTPAPIError(500) exception = "".join([ln for ln in traceback.format_exception(*exc_info)]) if status_code == 500 and not debug: self._send_error_email(exception) if debug: e.response["exception"] = exception self.clear() self.set_status(200) # always return 200 OK for API errors self.set_header("Content-Type", "application/json; charset=UTF-8") self.finish(str(e)) except Exception: logging.error(traceback.format_exc()) return super(APIHandler, self).write_error(status_code, **kwargs) 12年10月14⽇日星期⽇日
  • 10. Exception class HTTPAPIError(HTTPError): """API error handling exception API server always returns formatted JSON to client even there is an internal server error. """ def __init__(self, status_code=400, error_detail="", error_type="", notification="", response="", log_message=None, *args): super(HTTPAPIError, self).__init__(int(status_code), log_message, *args) self.error_type = error_type if error_type else _error_types.get(self.status_code, "unknow_error") self.error_detail = error_detail self.notification = {"message": notification} if notification else {} self.response = response if response else {} def __str__(self): err = {"meta": {"code": self.status_code, "errorType": self.error_type}} self._set_err(err, ["notification", "response"]) if self.error_detail: err["meta"]["errorDetail"] = self.error_detail return escape.json_encode(err) 12年10月14⽇日星期⽇日
  • 15. ⺴⽹网⻚页抓取 def update_server_status(): url = options.d3_server_status_url req = HTTPRequest(url=url) client = HTTPClient() response = client.fetch(req) if response.code == 200: status = _parse_server_status(response.body) 12年10月14⽇日星期⽇日
  • 16. ⺴⽹网⻚页解析 def _parse_server_status(body): status = {} q = pq(etree.fromstring(body)) boxes = q(".box") # category box for box in boxes: box_q = pq(etree.fromstring(etree.tostring(box))) category = box_q(".category")[0].text.strip() status[category] = {} servers = box_q(".server") for server in servers: server_q = pq(etree.fromstring(etree.tostring(server))) server_name = server_q(".server-name")[0].text.strip().replace(" ", "") if server_name: status_icon = server_q(".status-icon")[0] class_ = status_icon.get("class") if class_: st = 0 if "up" in class_: st = 1 status[category][server_name] = st return status 12年10月14⽇日星期⽇日
  • 17. @task 任务队列 def status_notification_task(changed_status): status_notifciation(changed_status) def status_notifciation(changed_status): notifications = {} for category, services in changed_status.iteritems(): for name, st in services.iteritems(): # just push notification about game server now if name == "GameServer": notifications[category] = st for category, st in notifications.iteritems(): status = "Available" if st else "Unavailable" offset = 0 limit = 200 while True: subscribers = load_model("subscribers").get_subscribers(limit, offset) if not subscribers: break for subscribe in subscribers: if category in subscribe.categorys: alert = _trans_alert("Diablo3 %s server status has changed to %s", category, status, subscribe.locale) apns_tasks.apns_push_task.delay(subscribe.token, {}, alert=alert, badge=1, sound="default") offset += len(subscribers) 12年10月14⽇日星期⽇日
  • 18. 其它 • Apple push notification • i18n • crontab 12年10月14⽇日星期⽇日
  • 19. 相关资源 • https://github.com/felinx/d3status • http://www.tornadoweb.org • http://www.tornadoweb.cn • http://tornado.poweredsites.org • http://tornadogists.org • http://en.wikipedia.org/wiki/ Representational_state_transfer 12年10月14⽇日星期⽇日
  • 20. Q&A @⻜飞⻰龙⾮非⻰龙 http://feilong.me/ 12年10月14⽇日星期⽇日