SlideShare a Scribd company logo
1 of 29
Download to read offline
RESTful webservices with
        Python
      For lazy developers
               or
    developers with deadlines
source: http://s3-ec.buzzfed.
com/static/enhanced/webdr01/2012/12/2/13/e
nhanced-buzz-wide-18383-1354473319-2.jpg
Who am I?


      Justyna Żarna
Woman in Django / Python World
       JavaScript freak

     @Ustinez


     http://solution4future.com
Content



1. REST software architecture.

2. Benchmarks - problem analysis.

3. Flask + SQLAlchemy.

4. Django & class-based views.
                                    }   case study
API


 XML/RPC               SOAP            REST


based on HTTP      based on HTTP
protocol           protocol or other
                   protocols
many restriction
on data types      synchronous         ???
synchronous        based on XML
                   and all xml
                   defects
What is so cool?

                REpresentational State Transfer
                                                }
                                         Resource
                                      http://a.com/resources/




http://a.com/resources/item1/     http://a.com/resources/item2/   http://a.com/resources/item3/


    Representation                      Representation                 Representation



      GET                       PUT                 POST          DELETE

                                  THE VERBS
What is so cool?

              REpresentational State Transfer

1. Scalability                   6. In HTTP context but not
                                 limited to this protocol.
2. Generalization of interface   7. Good designed interface.

3. Independence

4. Security

5. Simplicity
http://www.2010theyearinbooks.com/2012/12/december-beach-reads-for-australian.html


make your API RESTful and go to rest...
Benchmark JSON
 response for frameworks
 and languages.

 Python frameworks:

 * Django-stripped 13 269
 per second

 * Flask - 11 506 per sec

 * Django - 7122 per sec

http://www.techempower.com/blog/2013/04/05/frameworks-round-
2/
The source code and problems

         https://github.com/TechEmpower/FrameworkBenchmarks/
         http://www.techempower.com/blog/2013/04/05/frameworks-round-2/


In this souce code for flask and django isn't used
connection pool - cache of database connection.


                                      connection
 connection           database
                                      connection           database
                                      connection

 connection for each request is        connection are maintained for
 open and closed.                                 future
Solutions?

1. Database optimalization for PostgreSQL:
 ●  pgBouncer
 ●  pgPool




     http://www.askthepony.com/blog/2011/07/django-and-postgresql-improving-the-performance-with-no-effort-and-no-code/
Solutions?
               code profiler can tell us more...




2. JSON standard serialization in Python STD
library is slow, so we can improve performance by
using module ujson - ultra json.
Solutions?




3. Rendering template can be faster with template
engine jinja (inspired by Django templates)
Flask




●   "micro" does not means micro possibilities,
●   core is light, simple and extensible,
●   support many extensions in each layer (for
    example your database layer can by relational
    database or non-relational data persistence).
Case study - micro framework Flask

from sqlalchemy import Column, Integer, String
from newsletter.database import Base

class Member(Base):
   __tablename__ = 'newsletter_members'
   id = Column(Integer, primary_key=True)
   last_name = Column(String(50))
   first_name = Column(String(120))
   email = Column(String(120), unique=True)

  def __init__(self, last_name=None, first_name=None, email=None):
    self.last_name = last_name
    self.first_name = first_name
    self.email = email

  def __repr__(self):
    return '<Member %r>' % (self.last_name)
Case study - micro framework Flask

class API(MethodView):

  def get(self, member_id):
    if member_id is None:
       return Member.query.all()
    else:
        return Member.query.filter_by(id = member_id).first()
  def post(self, data ):
    member = Member(first_name = data['first_name'], email=data['email'])
    db.session.add(member)
    db.session.commit()
    return 'OK'

app.add_url_rule('/users/<int:user_id>', view_func=API.as_view('user_api'),
           methods=['GET', 'POST'])

#class flask.views.MethodView and recognizing each REST methods are based on generic
dispatch_request()
Case study - micro framework Flask




   It was simple and quick to code?


improve simplicity and spent time with...
           Flask RESTless
Flask RESTless - full script
import flask
import flask.ext.sqlalchemy
import flask.ext.restless
app = flask.Flask(__name__)
app.config['DEBUG'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = flask.ext.sqlalchemy.SQLAlchemy(app)

class Member(db/Model):
   __tablename__ = 'newsletter_members'          Too simple for real project.. ?
   id = db.Column(Integer, primary_key=True)
   last_name = db.Column(String(50))
   first_name = db.Column(String(120))
   email = db.Column(String(120), unique=True)

db.create_all()

manager = flask.ext.restless.APIManager(app, flask_sqlalchemy_db=db)

manager.create_api(Member, methods=['GET', 'POST'])

app.run()
Flask RESTless - more sugar

●   versioning:

    GET /api/member
    GET /api/member/(int: id)
    GET /api/member?q=<json>
    POST /api/member

    apimanager.create_api(Member, url_prefix='/api/v2')
    GET /api/v2/member


●   validation:
    manager.create_api(Member, methods=['GET', 'POST'], validation_exceptions=
    [ValidationError])

    { "validation_errors":
       {
         "email": "Email is not valid..",
       }
    }
Flask RESTless - more sugar

●   specify columns (include or exclude):

    apimanager.create_api(Member, include_columns = ['last_name', 'email'])


●   pagination:
    manager.create_api(Member, methods=['GET', 'POST'], results_per_page=2)

    { "validation_errors":
        {
          "age": "Must be an integer",
        }
    {
      "num_results": 6,
      "total_pages": 3,
      "page": 1,
      "objects": [
        {"last_name": "Kovalsky", "email": "kovalsky@gmail.com", "id": 1},
        {"last_name": "Novak", "email": "novak@gmail.com", "id": 2}
      ]
    }
Flask RESTless - more and more..
●   pre/post-processors:
    def pre_get_single(instid):
       # do something
       pass

    def pre_get_many(params):
       # do something
       pass

    # Create an API for the Member model.
    manager.create_api(Person, methods=['GET', 'POST'],
       # A list of preprocessors for each method.
       preprocessors={'GET_SINGLE': [pre_get_single], 'GET_MANY': [pre_get_many],})

●   Authentication:
    def auth_func(params):
       if not current_user.is_authenticated():
          raise ProcessingException(message='Not authenticated!')
       return NO_CHANGE
    manager.create_api(Person, preprocessors={'GET_SINGLE': [auth_func]})
Flask RESTless - more and more..
●   filtering:

    import requests
    import json

    url = 'http://127.0.0.1:5000/api/member'
    headers = {'Content-Type': 'application/json'}

    filters = [dict(email='email', op='like', val='%y%')]
    params = dict(q=json.dumps(dict(filters=filters)))
    response = requests.get(url, params=params, headers=headers)

    GET /api/member?q={"filters":[{"name":"email", "op":"like", "val": "kovalsky"}]}


    OPERATORS examples:
     ○ ==, eq, !=, neq,
     ○ >, gte, <, lte                                FOR RELATIONS:
     ○ in, not_in                                     ● column__column example:
                                                         member__group
     ○ is_null
     ○ like
     ○ has
     ○ any
What about Django?


●   Define your model:

    from django.db import models

    class Member(models.Model):
       last_name = models.CharField(max_length = 100, verbose_name = "Last name")
       first_name = models.CharField(max_length = 100, verbose_name = "First name")
       email = models.EmailField(max_length = 100, verbose_name = "Email")

    def __unicode__(self):
      return self.email

      class Meta:
         verbose_name = "Newsletter member"
         verbose_name_plural = "Newsletter members"
What about Django?
●   Define your model serializer:
    class MemberSerializer(serializers.ModelSerializer):
       class Meta:
          model = Member
          fields = ('last_name', 'first_name', 'email')


●   Working with serializers:
    from   newsletter.models import Member
    from   newsletter.serializers import MemberSerializer
    from   rest_framework.renderers import JSONRenderer
    from   rest_framework.parsers import JSONParser

    member = Member(last_name='Kovalsky', first_name= 'Johny', 'email' = 'kovalsky@gmail.
    com')
    member.save()

    serializer = MemberSerializer(member)
    content = JSONRenderer().render(serializer.data)
    # content: {"pk": 2, "last_name": "Kovalsky", "first_name="Johny", email =
    "kovalsky@gmail.com"}, more object in format [{'foo': 'bar'}, {'foo': 'bar'}]
What about Django?
●   Define your class-based views:
    class MemberDetail(APIView):
       """
       Retrieve, update or delete a member instance.
       """
       def get_object(self, pk):
           try:
              return Member.objects.get(pk=pk)
           except Member.DoesNotExist:
              raise Http404

      def get(self, request, pk, format=None):
         member = self.get_object(pk)
         serializer = MemberSerializer(member)
         return Response(member.data)
What about Django?
●   Define your class-based views:

      def put(self, request, pk, format=None):
         member = self.get_object(pk)
         serializer = MemberSerializer(member, data=request.DATA)
         if serializer.is_valid():
             serializer.save()
             return Response(serializer.data)
         return Response(serializer.errors, status=status.
    HTTP_400_BAD_REQUEST)

       def delete(self, request, pk, format=None):
          member = self.get_object(pk)
          member.delete()
          return Response(status=status.HTTP_204_NO_CONTENT)
What about Django?
●   Or generic views:
    from newsletter.models import Member
    from newsletter.serializers import MemberSerializer
    from rest_framework import generics

    class MemberList(generics.ListCreateAPIView):
       model = Member
       serializer_class = MemberSerializer

    class MemberDetail(generics.RetrieveUpdateDestroyAPIView):
       model = Member
       serializer_class = MemberSerializer


●   URLs patterns:

    urlpatterns = patterns('',
       url(r'^members/$', views.MeberList.as_view()),
       url(r'^members/(?P<pk>[0-9]+)/$', views.MemberDetail.as_view()),
    )
RESTful API - done


     http://sarahwmackey.files.wordpress.com/
Thank you for your
    attention




   http://solution4future.com/

More Related Content

What's hot

ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web APIhabib_786
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced JavascriptAdieu
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object ModelWebStackAcademy
 
A Basic Django Introduction
A Basic Django IntroductionA Basic Django Introduction
A Basic Django IntroductionGanga Ram
 
Rapid JCR applications development with Sling
Rapid JCR applications development with SlingRapid JCR applications development with Sling
Rapid JCR applications development with SlingBertrand Delacretaz
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to DjangoKnoldus Inc.
 
REST API and CRUD
REST API and CRUDREST API and CRUD
REST API and CRUDPrem Sanil
 
What is REST API? REST API Concepts and Examples | Edureka
What is REST API? REST API Concepts and Examples | EdurekaWhat is REST API? REST API Concepts and Examples | Edureka
What is REST API? REST API Concepts and Examples | EdurekaEdureka!
 
React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥Remo Jansen
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!Jakub Kubrynski
 

What's hot (20)

jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web API
 
Flask – Python
Flask – PythonFlask – Python
Flask – Python
 
Spring Security 5
Spring Security 5Spring Security 5
Spring Security 5
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
 
JUnit 5
JUnit 5JUnit 5
JUnit 5
 
A Basic Django Introduction
A Basic Django IntroductionA Basic Django Introduction
A Basic Django Introduction
 
An Introduction To REST API
An Introduction To REST APIAn Introduction To REST API
An Introduction To REST API
 
Rapid JCR applications development with Sling
Rapid JCR applications development with SlingRapid JCR applications development with Sling
Rapid JCR applications development with Sling
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
SQLITE Android
SQLITE AndroidSQLITE Android
SQLITE Android
 
PHP - Introduction to PHP AJAX
PHP -  Introduction to PHP AJAXPHP -  Introduction to PHP AJAX
PHP - Introduction to PHP AJAX
 
Spring Core
Spring CoreSpring Core
Spring Core
 
Rest in flask
Rest in flaskRest in flask
Rest in flask
 
REST API and CRUD
REST API and CRUDREST API and CRUD
REST API and CRUD
 
What is REST API? REST API Concepts and Examples | Edureka
What is REST API? REST API Concepts and Examples | EdurekaWhat is REST API? REST API Concepts and Examples | Edureka
What is REST API? REST API Concepts and Examples | Edureka
 
React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥
 
Expressjs
ExpressjsExpressjs
Expressjs
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!
 

Viewers also liked

Building Automated REST APIs with Python
Building Automated REST APIs with PythonBuilding Automated REST APIs with Python
Building Automated REST APIs with PythonJeff Knupp
 
Developing RESTful Web APIs with Python, Flask and MongoDB
Developing RESTful Web APIs with Python, Flask and MongoDBDeveloping RESTful Web APIs with Python, Flask and MongoDB
Developing RESTful Web APIs with Python, Flask and MongoDBNicola Iarocci
 
Web backends development using Python
Web backends development using PythonWeb backends development using Python
Web backends development using PythonAyun Park
 
Ten Reasons Developers Hate Your API
Ten Reasons Developers Hate Your APITen Reasons Developers Hate Your API
Ten Reasons Developers Hate Your APIJohn Musser
 
Python tools for testing web services over HTTP
Python tools for testing web services over HTTPPython tools for testing web services over HTTP
Python tools for testing web services over HTTPMykhailo Kolesnyk
 
REST Easy with Django-Rest-Framework
REST Easy with Django-Rest-FrameworkREST Easy with Django-Rest-Framework
REST Easy with Django-Rest-FrameworkMarcel Chastain
 
Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - ...
Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - ...Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - ...
Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - ...Innovecs
 
Flask RESTful Flask HTTPAuth
Flask RESTful Flask HTTPAuthFlask RESTful Flask HTTPAuth
Flask RESTful Flask HTTPAuthEueung Mulyana
 
Design Beautiful REST + JSON APIs
Design Beautiful REST + JSON APIsDesign Beautiful REST + JSON APIs
Design Beautiful REST + JSON APIsStormpath
 
Python and Flask introduction for my classmates Презентация и введение в flask
Python and Flask introduction for my classmates Презентация и введение в flaskPython and Flask introduction for my classmates Презентация и введение в flask
Python and Flask introduction for my classmates Презентация и введение в flaskNikita Lozhnikov
 
Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Eric Palakovich Carr
 
Microservices with Swagger, Flask and Docker
Microservices with Swagger, Flask and DockerMicroservices with Swagger, Flask and Docker
Microservices with Swagger, Flask and DockerDhilipsiva DS
 
Rest API using Flask & SqlAlchemy
Rest API using Flask & SqlAlchemyRest API using Flask & SqlAlchemy
Rest API using Flask & SqlAlchemyAlessandro Cucci
 
Scalable Django Architecture
Scalable Django ArchitectureScalable Django Architecture
Scalable Django ArchitectureRami Sayar
 
DEVNET-1001 Coding 101: How to Call REST APIs from a REST Client and Python
DEVNET-1001 Coding 101: How to Call REST APIs from a REST Client and PythonDEVNET-1001 Coding 101: How to Call REST APIs from a REST Client and Python
DEVNET-1001 Coding 101: How to Call REST APIs from a REST Client and PythonCisco DevNet
 

Viewers also liked (20)

Building Automated REST APIs with Python
Building Automated REST APIs with PythonBuilding Automated REST APIs with Python
Building Automated REST APIs with Python
 
Rest api with Python
Rest api with PythonRest api with Python
Rest api with Python
 
Developing RESTful Web APIs with Python, Flask and MongoDB
Developing RESTful Web APIs with Python, Flask and MongoDBDeveloping RESTful Web APIs with Python, Flask and MongoDB
Developing RESTful Web APIs with Python, Flask and MongoDB
 
Web backends development using Python
Web backends development using PythonWeb backends development using Python
Web backends development using Python
 
Ten Reasons Developers Hate Your API
Ten Reasons Developers Hate Your APITen Reasons Developers Hate Your API
Ten Reasons Developers Hate Your API
 
Python tools for testing web services over HTTP
Python tools for testing web services over HTTPPython tools for testing web services over HTTP
Python tools for testing web services over HTTP
 
REST Easy with Django-Rest-Framework
REST Easy with Django-Rest-FrameworkREST Easy with Django-Rest-Framework
REST Easy with Django-Rest-Framework
 
Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - ...
Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - ...Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - ...
Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - ...
 
JSON and REST
JSON and RESTJSON and REST
JSON and REST
 
Flask RESTful Flask HTTPAuth
Flask RESTful Flask HTTPAuthFlask RESTful Flask HTTPAuth
Flask RESTful Flask HTTPAuth
 
Design Beautiful REST + JSON APIs
Design Beautiful REST + JSON APIsDesign Beautiful REST + JSON APIs
Design Beautiful REST + JSON APIs
 
Python and Flask introduction for my classmates Презентация и введение в flask
Python and Flask introduction for my classmates Презентация и введение в flaskPython and Flask introduction for my classmates Презентация и введение в flask
Python and Flask introduction for my classmates Презентация и введение в flask
 
Flask vs. Django
Flask vs. DjangoFlask vs. Django
Flask vs. Django
 
Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!
 
Microservices with Swagger, Flask and Docker
Microservices with Swagger, Flask and DockerMicroservices with Swagger, Flask and Docker
Microservices with Swagger, Flask and Docker
 
Rest in flask
Rest in flaskRest in flask
Rest in flask
 
Rest API using Flask & SqlAlchemy
Rest API using Flask & SqlAlchemyRest API using Flask & SqlAlchemy
Rest API using Flask & SqlAlchemy
 
Scalable Django Architecture
Scalable Django ArchitectureScalable Django Architecture
Scalable Django Architecture
 
DEVNET-1001 Coding 101: How to Call REST APIs from a REST Client and Python
DEVNET-1001 Coding 101: How to Call REST APIs from a REST Client and PythonDEVNET-1001 Coding 101: How to Call REST APIs from a REST Client and Python
DEVNET-1001 Coding 101: How to Call REST APIs from a REST Client and Python
 
RESTful API Design, Second Edition
RESTful API Design, Second EditionRESTful API Design, Second Edition
RESTful API Design, Second Edition
 

Similar to Python RESTful webservices with Python: Flask and Django solutions

Rapid java backend and api development for mobile devices
Rapid java backend and api development for mobile devicesRapid java backend and api development for mobile devices
Rapid java backend and api development for mobile devicesciklum_ods
 
540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdfhamzadamani7
 
Laurens Van Den Oever Xopus Presentation
Laurens Van Den Oever Xopus PresentationLaurens Van Den Oever Xopus Presentation
Laurens Van Den Oever Xopus PresentationAjax Experience 2009
 
Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLsintelliyole
 
Declarative Services - Dependency Injection OSGi Style
Declarative Services - Dependency Injection OSGi StyleDeclarative Services - Dependency Injection OSGi Style
Declarative Services - Dependency Injection OSGi StyleFelix Meschberger
 
Declarative Services - Dependency Injection OSGi Style
Declarative Services - Dependency Injection OSGi StyleDeclarative Services - Dependency Injection OSGi Style
Declarative Services - Dependency Injection OSGi StyleFelix Meschberger
 
Build restful ap is with python and flask
Build restful ap is with python and flaskBuild restful ap is with python and flask
Build restful ap is with python and flaskJeetendra singh
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...Fabio Franzini
 
Simplify your professional web development with symfony
Simplify your professional web development with symfonySimplify your professional web development with symfony
Simplify your professional web development with symfonyFrancois Zaninotto
 
Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's CodeWildan Maulana
 
Osiąganie mądrej architektury z Symfony2
Osiąganie mądrej architektury z Symfony2 Osiąganie mądrej architektury z Symfony2
Osiąganie mądrej architektury z Symfony2 3camp
 
Flask Introduction - Python Meetup
Flask Introduction - Python MeetupFlask Introduction - Python Meetup
Flask Introduction - Python MeetupAreski Belaid
 
JavaOne 2009 - TS-5276 - RESTful Protocol Buffers
JavaOne 2009 - TS-5276 - RESTful  Protocol BuffersJavaOne 2009 - TS-5276 - RESTful  Protocol Buffers
JavaOne 2009 - TS-5276 - RESTful Protocol BuffersMatt O'Keefe
 
PyCon US 2012 - State of WSGI 2
PyCon US 2012 - State of WSGI 2PyCon US 2012 - State of WSGI 2
PyCon US 2012 - State of WSGI 2Graham Dumpleton
 
SCR Annotations for Fun and Profit
SCR Annotations for Fun and ProfitSCR Annotations for Fun and Profit
SCR Annotations for Fun and ProfitMike Pfaff
 
Practical catalyst
Practical catalystPractical catalyst
Practical catalystdwm042
 
AEM Sightly Deep Dive
AEM Sightly Deep DiveAEM Sightly Deep Dive
AEM Sightly Deep DiveGabriel Walt
 

Similar to Python RESTful webservices with Python: Flask and Django solutions (20)

Rapid java backend and api development for mobile devices
Rapid java backend and api development for mobile devicesRapid java backend and api development for mobile devices
Rapid java backend and api development for mobile devices
 
540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf
 
Laurens Van Den Oever Xopus Presentation
Laurens Van Den Oever Xopus PresentationLaurens Van Den Oever Xopus Presentation
Laurens Van Den Oever Xopus Presentation
 
Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLs
 
Declarative Services - Dependency Injection OSGi Style
Declarative Services - Dependency Injection OSGi StyleDeclarative Services - Dependency Injection OSGi Style
Declarative Services - Dependency Injection OSGi Style
 
Declarative Services - Dependency Injection OSGi Style
Declarative Services - Dependency Injection OSGi StyleDeclarative Services - Dependency Injection OSGi Style
Declarative Services - Dependency Injection OSGi Style
 
Build restful ap is with python and flask
Build restful ap is with python and flaskBuild restful ap is with python and flask
Build restful ap is with python and flask
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
 
Simplify your professional web development with symfony
Simplify your professional web development with symfonySimplify your professional web development with symfony
Simplify your professional web development with symfony
 
Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's Code
 
AD102 - Break out of the Box
AD102 - Break out of the BoxAD102 - Break out of the Box
AD102 - Break out of the Box
 
Osiąganie mądrej architektury z Symfony2
Osiąganie mądrej architektury z Symfony2 Osiąganie mądrej architektury z Symfony2
Osiąganie mądrej architektury z Symfony2
 
Flask Introduction - Python Meetup
Flask Introduction - Python MeetupFlask Introduction - Python Meetup
Flask Introduction - Python Meetup
 
JavaOne 2009 - TS-5276 - RESTful Protocol Buffers
JavaOne 2009 - TS-5276 - RESTful  Protocol BuffersJavaOne 2009 - TS-5276 - RESTful  Protocol Buffers
JavaOne 2009 - TS-5276 - RESTful Protocol Buffers
 
Gohan
GohanGohan
Gohan
 
PyCon US 2012 - State of WSGI 2
PyCon US 2012 - State of WSGI 2PyCon US 2012 - State of WSGI 2
PyCon US 2012 - State of WSGI 2
 
SCR Annotations for Fun and Profit
SCR Annotations for Fun and ProfitSCR Annotations for Fun and Profit
SCR Annotations for Fun and Profit
 
Switch to Backend 2023
Switch to Backend 2023Switch to Backend 2023
Switch to Backend 2023
 
Practical catalyst
Practical catalystPractical catalyst
Practical catalyst
 
AEM Sightly Deep Dive
AEM Sightly Deep DiveAEM Sightly Deep Dive
AEM Sightly Deep Dive
 

Recently uploaded

Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 

Recently uploaded (20)

Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 

Python RESTful webservices with Python: Flask and Django solutions

  • 1. RESTful webservices with Python For lazy developers or developers with deadlines
  • 3. Who am I? Justyna Żarna Woman in Django / Python World JavaScript freak @Ustinez http://solution4future.com
  • 4. Content 1. REST software architecture. 2. Benchmarks - problem analysis. 3. Flask + SQLAlchemy. 4. Django & class-based views. } case study
  • 5. API XML/RPC SOAP REST based on HTTP based on HTTP protocol protocol or other protocols many restriction on data types synchronous ??? synchronous based on XML and all xml defects
  • 6. What is so cool? REpresentational State Transfer } Resource http://a.com/resources/ http://a.com/resources/item1/ http://a.com/resources/item2/ http://a.com/resources/item3/ Representation Representation Representation GET PUT POST DELETE THE VERBS
  • 7. What is so cool? REpresentational State Transfer 1. Scalability 6. In HTTP context but not limited to this protocol. 2. Generalization of interface 7. Good designed interface. 3. Independence 4. Security 5. Simplicity
  • 9. Benchmark JSON response for frameworks and languages. Python frameworks: * Django-stripped 13 269 per second * Flask - 11 506 per sec * Django - 7122 per sec http://www.techempower.com/blog/2013/04/05/frameworks-round- 2/
  • 10. The source code and problems https://github.com/TechEmpower/FrameworkBenchmarks/ http://www.techempower.com/blog/2013/04/05/frameworks-round-2/ In this souce code for flask and django isn't used connection pool - cache of database connection. connection connection database connection database connection connection for each request is connection are maintained for open and closed. future
  • 11. Solutions? 1. Database optimalization for PostgreSQL: ● pgBouncer ● pgPool http://www.askthepony.com/blog/2011/07/django-and-postgresql-improving-the-performance-with-no-effort-and-no-code/
  • 12. Solutions? code profiler can tell us more... 2. JSON standard serialization in Python STD library is slow, so we can improve performance by using module ujson - ultra json.
  • 13. Solutions? 3. Rendering template can be faster with template engine jinja (inspired by Django templates)
  • 14. Flask ● "micro" does not means micro possibilities, ● core is light, simple and extensible, ● support many extensions in each layer (for example your database layer can by relational database or non-relational data persistence).
  • 15. Case study - micro framework Flask from sqlalchemy import Column, Integer, String from newsletter.database import Base class Member(Base): __tablename__ = 'newsletter_members' id = Column(Integer, primary_key=True) last_name = Column(String(50)) first_name = Column(String(120)) email = Column(String(120), unique=True) def __init__(self, last_name=None, first_name=None, email=None): self.last_name = last_name self.first_name = first_name self.email = email def __repr__(self): return '<Member %r>' % (self.last_name)
  • 16. Case study - micro framework Flask class API(MethodView): def get(self, member_id): if member_id is None: return Member.query.all() else: return Member.query.filter_by(id = member_id).first() def post(self, data ): member = Member(first_name = data['first_name'], email=data['email']) db.session.add(member) db.session.commit() return 'OK' app.add_url_rule('/users/<int:user_id>', view_func=API.as_view('user_api'), methods=['GET', 'POST']) #class flask.views.MethodView and recognizing each REST methods are based on generic dispatch_request()
  • 17. Case study - micro framework Flask It was simple and quick to code? improve simplicity and spent time with... Flask RESTless
  • 18. Flask RESTless - full script import flask import flask.ext.sqlalchemy import flask.ext.restless app = flask.Flask(__name__) app.config['DEBUG'] = True app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' db = flask.ext.sqlalchemy.SQLAlchemy(app) class Member(db/Model): __tablename__ = 'newsletter_members' Too simple for real project.. ? id = db.Column(Integer, primary_key=True) last_name = db.Column(String(50)) first_name = db.Column(String(120)) email = db.Column(String(120), unique=True) db.create_all() manager = flask.ext.restless.APIManager(app, flask_sqlalchemy_db=db) manager.create_api(Member, methods=['GET', 'POST']) app.run()
  • 19. Flask RESTless - more sugar ● versioning: GET /api/member GET /api/member/(int: id) GET /api/member?q=<json> POST /api/member apimanager.create_api(Member, url_prefix='/api/v2') GET /api/v2/member ● validation: manager.create_api(Member, methods=['GET', 'POST'], validation_exceptions= [ValidationError]) { "validation_errors": { "email": "Email is not valid..", } }
  • 20. Flask RESTless - more sugar ● specify columns (include or exclude): apimanager.create_api(Member, include_columns = ['last_name', 'email']) ● pagination: manager.create_api(Member, methods=['GET', 'POST'], results_per_page=2) { "validation_errors": { "age": "Must be an integer", } { "num_results": 6, "total_pages": 3, "page": 1, "objects": [ {"last_name": "Kovalsky", "email": "kovalsky@gmail.com", "id": 1}, {"last_name": "Novak", "email": "novak@gmail.com", "id": 2} ] }
  • 21. Flask RESTless - more and more.. ● pre/post-processors: def pre_get_single(instid): # do something pass def pre_get_many(params): # do something pass # Create an API for the Member model. manager.create_api(Person, methods=['GET', 'POST'], # A list of preprocessors for each method. preprocessors={'GET_SINGLE': [pre_get_single], 'GET_MANY': [pre_get_many],}) ● Authentication: def auth_func(params): if not current_user.is_authenticated(): raise ProcessingException(message='Not authenticated!') return NO_CHANGE manager.create_api(Person, preprocessors={'GET_SINGLE': [auth_func]})
  • 22. Flask RESTless - more and more.. ● filtering: import requests import json url = 'http://127.0.0.1:5000/api/member' headers = {'Content-Type': 'application/json'} filters = [dict(email='email', op='like', val='%y%')] params = dict(q=json.dumps(dict(filters=filters))) response = requests.get(url, params=params, headers=headers) GET /api/member?q={"filters":[{"name":"email", "op":"like", "val": "kovalsky"}]} OPERATORS examples: ○ ==, eq, !=, neq, ○ >, gte, <, lte FOR RELATIONS: ○ in, not_in ● column__column example: member__group ○ is_null ○ like ○ has ○ any
  • 23. What about Django? ● Define your model: from django.db import models class Member(models.Model): last_name = models.CharField(max_length = 100, verbose_name = "Last name") first_name = models.CharField(max_length = 100, verbose_name = "First name") email = models.EmailField(max_length = 100, verbose_name = "Email") def __unicode__(self): return self.email class Meta: verbose_name = "Newsletter member" verbose_name_plural = "Newsletter members"
  • 24. What about Django? ● Define your model serializer: class MemberSerializer(serializers.ModelSerializer): class Meta: model = Member fields = ('last_name', 'first_name', 'email') ● Working with serializers: from newsletter.models import Member from newsletter.serializers import MemberSerializer from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser member = Member(last_name='Kovalsky', first_name= 'Johny', 'email' = 'kovalsky@gmail. com') member.save() serializer = MemberSerializer(member) content = JSONRenderer().render(serializer.data) # content: {"pk": 2, "last_name": "Kovalsky", "first_name="Johny", email = "kovalsky@gmail.com"}, more object in format [{'foo': 'bar'}, {'foo': 'bar'}]
  • 25. What about Django? ● Define your class-based views: class MemberDetail(APIView): """ Retrieve, update or delete a member instance. """ def get_object(self, pk): try: return Member.objects.get(pk=pk) except Member.DoesNotExist: raise Http404 def get(self, request, pk, format=None): member = self.get_object(pk) serializer = MemberSerializer(member) return Response(member.data)
  • 26. What about Django? ● Define your class-based views: def put(self, request, pk, format=None): member = self.get_object(pk) serializer = MemberSerializer(member, data=request.DATA) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status. HTTP_400_BAD_REQUEST) def delete(self, request, pk, format=None): member = self.get_object(pk) member.delete() return Response(status=status.HTTP_204_NO_CONTENT)
  • 27. What about Django? ● Or generic views: from newsletter.models import Member from newsletter.serializers import MemberSerializer from rest_framework import generics class MemberList(generics.ListCreateAPIView): model = Member serializer_class = MemberSerializer class MemberDetail(generics.RetrieveUpdateDestroyAPIView): model = Member serializer_class = MemberSerializer ● URLs patterns: urlpatterns = patterns('', url(r'^members/$', views.MeberList.as_view()), url(r'^members/(?P<pk>[0-9]+)/$', views.MemberDetail.as_view()), )
  • 28. RESTful API - done http://sarahwmackey.files.wordpress.com/
  • 29. Thank you for your attention http://solution4future.com/