SlideShare une entreprise Scribd logo
1  sur  41
Télécharger pour lire hors ligne
Discover GraphQL with Python,
Graphene and Odoo
#OdooExperience 2019-10-03
Stéphane Bidoul <stephane.bidoul@acsone.eu>
Version 1.0.0
A short story
• Why this talk…
2 / 46
/me in a nutshell
• @sbidoul
• CTO of (https://acsone.eu)
• Elected Board Member of (https://odoo-community.org)
• Python since 1996 (1.4)
• FLOSS, because…
• Have used a lot of RPC mechanisms
3 / 46
Content
• What is GraphQL?
• Demo
• How to… for Odoo with Graphene
• How is GraphQL different?
• Caveats and thoughts
• Resources
• Q&A
4 / 46
What is GraphQL?
• Yet another Remote Procedure Call protocol?
• Open Sourced by Facebook in 2015
• Basic characteristics
• Requests: GraphQL data query language
• Responses: json
• Schema: GraphQL schema language
• Transport: usually HTTPS (GET, POST)
• Variety of server side libs, no need for client side lib
5 / 46
Demo
• GraphQL Schema for Odoo Partners and Contacts.
6 / 46
How to… for Odoo with Graphene
import graphene
class Country(graphene.ObjectType):
code = graphene.String(required=True)
name = graphene.String(required=True)
24 / 46
How to… for Odoo with Graphene
from odoo.addons.graphql_base import OdooObjectType
class Partner(OdooObjectType):
name = graphene.String(required=True)
street = graphene.String()
street2 = graphene.String()
city = graphene.String()
zip = graphene.String()
email = graphene.String()
phone = graphene.String()
is_company = graphene.Boolean(required=True)
# ...
25 / 46
How to… for Odoo with Graphene
class Partner(OdooObjectType):
# ...
country = graphene.Field(Country)
@staticmethod
def resolve_country(root, info):
return root.country_id or None
26 / 46
How to… for Odoo with Graphene
class Partner(OdooObjectType):
# ...
contacts = graphene.List(
graphene.NonNull(lambda: Partner),
required=True,
)
def resolve_contacts(root, info):
return root.child_ids
27 / 46
How to… for Odoo with Graphene
class Query(graphene.ObjectType):
all_partners = graphene.List(
graphene.NonNull(Partner),
required=True,
companies_only=graphene.Boolean(),
limit=graphene.Int(),
offset=graphene.Int(),
)
# ...
28 / 46
How to… for Odoo with Graphene
class Query(graphene.ObjectType):
# ...
def resolve_all_partners(
root, info, companies_only=False, limit=limit, offset=offset
):
# ... check for max limit
domain = []
if companies_only:
domain.append(("is_company", "=", True))
ResPartner = info.context["env"]["res.partner"]
return ResPartner.search(domain, limit=limit, offset=offset)
29 / 46
How to… for Odoo with Graphene
schema = graphene.Schema(query=Query)
30 / 46
How to… for Odoo with Graphene
from odoo import http
from odoo.addons.graphql_base import GraphQLControllerMixin
from ..schema import schema
class GraphQLController(http.Controller, GraphQLControllerMixin):
@http.route("/graphiql/demo", auth="user") # GraphiQL IDE
def graphiql(self, **kwargs):
return self._handle_graphiql_request(schema)
@http.route("/graphql/demo", auth="user")
def graphql(self, **kwargs):
return self._handle_graphql_request(schema)
31 / 46
How is GraphQL different? A long ancestry
• ASN.1, DCOM, CORBA, SOAP, REST+OpenAPI and many more
• Some sort of schema language
• Schema is machine readable (eg for automatic message validation)
• “On the wire” representation of corresponding messages
• Rigid request/response data structures
• The service developer interprets and validates the request, does stuff,
and prepares the response
32 / 46
How is GraphQL different? What about SQL?
• Machine readable schema
• “On the wire” message representation is proprietary (database
“drivers” instead)
• Flexible queries, written by the client developer
• There is no service developer, the database does it (stored
procedures fall in previous category)
33 / 46
How is GraphQL different?
• Client-side freedom of SQL.
• Server-side freedom of REST.
34 / 46
Caveats and thoughts: a better REST?
• What is REST?
• REST + OpenAPI
• Crafting a pure REST API is an art that few master
• GraphQL breaks HTTP semantics
• Little leverage of HTTP infrastructure (caching, firewalls, etc)
• With pure REST it’s “easy”, see above
• Attention to wild clients, complex queries
• As always, it’s a matter of tradeoffs
35 / 46
Caveats and thoughts: Performance
Beware of naive implementation of resolvers!
DON’T (one database query per returned record):
def resolve_contacts(root, info):
ResPartner = info.context["env"]["res.partner"]
return ResPartner.search([('parent_id', '=', root.id)])
DO (use ORM prefetching strategies):
def resolve_contacts(root, info):
return root.child_ids
36 / 46
Caveats and thoughts: Façadism
• Temptation to expose all your domain model?
• Easy with generic GraphQL adapters (Django, SQLAlchemy, …)
• Should be quite easy for Odoo too
• It depends on the use case
• Often better to create a façade dedicated to the client use cases
• Don’t expose your guts and break clients when your domain
model changes
37 / 46
Caveats and thoughts: Access Control
• With traditional RPC (eg REST), access control is typically done at the
façade/service level
• GraphQL typically binds at the domain model level
• Built-in security in your domain model or data sources?
38 / 46
Key takeaways
• GraphQL is easier than it sounds, try it!
• Powerful alternative to REST
• Very easy to integrate in any Python web application thanks to
Graphene
• High productivity for backend devs
• High flexibility to frontend devs
39 / 46
Resources
• Start here
• https://graphql.org/learn/
• With Python
• https://graphene-python.org/
• Incl. support for different frameworks (eg Django, SQLAlchemy)
• With Odoo
• https://pypi.org/project/odoo12-addon-graphql-base/
• https://pypi.org/project/odoo12-addon-graphql-demo/
40 / 46
Questions?
@sbidoul
stephane.bidoul@acsone.eu

Contenu connexe

Tendances

Tendances (20)

Impact of the New ORM on Your Modules
Impact of the New ORM on Your ModulesImpact of the New ORM on Your Modules
Impact of the New ORM on Your Modules
 
Using runbot to test all your developments automatically
Using runbot to test all your developments automaticallyUsing runbot to test all your developments automatically
Using runbot to test all your developments automatically
 
Common Performance Pitfalls in Odoo apps
Common Performance Pitfalls in Odoo appsCommon Performance Pitfalls in Odoo apps
Common Performance Pitfalls in Odoo apps
 
How to Run a Process with Odoo and Process Maker
How to Run a Process with Odoo and Process MakerHow to Run a Process with Odoo and Process Maker
How to Run a Process with Odoo and Process Maker
 
REST Easy with Django-Rest-Framework
REST Easy with Django-Rest-FrameworkREST Easy with Django-Rest-Framework
REST Easy with Django-Rest-Framework
 
Odoo Experience 2018 - How to Break Odoo Security (or how to prevent it)
Odoo Experience 2018 - How to Break Odoo Security (or how to prevent it)Odoo Experience 2018 - How to Break Odoo Security (or how to prevent it)
Odoo Experience 2018 - How to Break Odoo Security (or how to prevent it)
 
Angular js routing options
Angular js routing optionsAngular js routing options
Angular js routing options
 
The Odoo JS Framework
The Odoo JS FrameworkThe Odoo JS Framework
The Odoo JS Framework
 
SQL Server에서 Django를 추구하면 안 되는 걸까?
SQL Server에서 Django를 추구하면 안 되는 걸까?SQL Server에서 Django를 추구하면 안 되는 걸까?
SQL Server에서 Django를 추구하면 안 되는 걸까?
 
Asynchronous JS in Odoo
Asynchronous JS in OdooAsynchronous JS in Odoo
Asynchronous JS in Odoo
 
Say Goodbye to Excel with the New built-in Odoo Spreadsheets
Say Goodbye to Excel with the New built-in Odoo SpreadsheetsSay Goodbye to Excel with the New built-in Odoo Spreadsheets
Say Goodbye to Excel with the New built-in Odoo Spreadsheets
 
Best Tools for first time Odoo Development
Best Tools for first time Odoo DevelopmentBest Tools for first time Odoo Development
Best Tools for first time Odoo Development
 
Tutorial: Develop an App with the Odoo Framework
Tutorial: Develop an App with the Odoo FrameworkTutorial: Develop an App with the Odoo Framework
Tutorial: Develop an App with the Odoo Framework
 
API Docs with OpenAPI 3.0
API Docs with OpenAPI 3.0API Docs with OpenAPI 3.0
API Docs with OpenAPI 3.0
 
How to Design Resilient Odoo Crons
How to Design Resilient Odoo CronsHow to Design Resilient Odoo Crons
How to Design Resilient Odoo Crons
 
Odoo 3D Product View with Google Model-Viewer
Odoo 3D Product View with Google Model-ViewerOdoo 3D Product View with Google Model-Viewer
Odoo 3D Product View with Google Model-Viewer
 
Swagger UI
Swagger UISwagger UI
Swagger UI
 
Odoo's Test Framework - Learn Best Practices
Odoo's Test Framework - Learn Best PracticesOdoo's Test Framework - Learn Best Practices
Odoo's Test Framework - Learn Best Practices
 
Writing Reusable Web Components with jQuery and jQuery UI
Writing Reusable Web Components with jQuery and jQuery UIWriting Reusable Web Components with jQuery and jQuery UI
Writing Reusable Web Components with jQuery and jQuery UI
 
Node.js Event Emitter
Node.js Event EmitterNode.js Event Emitter
Node.js Event Emitter
 

Similaire à Discover GraphQL with Python, Graphene and Odoo

OpenERP Technical Memento
OpenERP Technical MementoOpenERP Technical Memento
OpenERP Technical Memento
Odoo
 
GDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App EngineGDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App Engine
Yared Ayalew
 
Coder Presentation Szeged
Coder Presentation SzegedCoder Presentation Szeged
Coder Presentation Szeged
Doug Green
 
A gentle intro to the Django Framework
A gentle intro to the Django FrameworkA gentle intro to the Django Framework
A gentle intro to the Django Framework
Ricardo Soares
 
Python & Django TTT
Python & Django TTTPython & Django TTT
Python & Django TTT
kevinvw
 

Similaire à Discover GraphQL with Python, Graphene and Odoo (20)

Cassandra drivers and libraries
Cassandra drivers and librariesCassandra drivers and libraries
Cassandra drivers and libraries
 
More about PHP
More about PHPMore about PHP
More about PHP
 
OpenERP Technical Memento
OpenERP Technical MementoOpenERP Technical Memento
OpenERP Technical Memento
 
GDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App EngineGDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App Engine
 
PGQL: A Language for Graphs
PGQL: A Language for GraphsPGQL: A Language for Graphs
PGQL: A Language for Graphs
 
Coder Presentation Szeged
Coder Presentation SzegedCoder Presentation Szeged
Coder Presentation Szeged
 
Introduction to Google App Engine with Python
Introduction to Google App Engine with PythonIntroduction to Google App Engine with Python
Introduction to Google App Engine with Python
 
The goodies of zope, pyramid, and plone (2)
The goodies of zope, pyramid, and plone (2)The goodies of zope, pyramid, and plone (2)
The goodies of zope, pyramid, and plone (2)
 
Python and Oracle : allies for best of data management
Python and Oracle : allies for best of data managementPython and Oracle : allies for best of data management
Python and Oracle : allies for best of data management
 
A gentle intro to the Django Framework
A gentle intro to the Django FrameworkA gentle intro to the Django Framework
A gentle intro to the Django Framework
 
web2py:Web development like a boss
web2py:Web development like a bossweb2py:Web development like a boss
web2py:Web development like a boss
 
Python & Django TTT
Python & Django TTTPython & Django TTT
Python & Django TTT
 
Mustache
MustacheMustache
Mustache
 
Open erp technical_memento_v0.6.3_a4
Open erp technical_memento_v0.6.3_a4Open erp technical_memento_v0.6.3_a4
Open erp technical_memento_v0.6.3_a4
 
Develop an App with the Odoo Framework
Develop an App with the Odoo FrameworkDevelop an App with the Odoo Framework
Develop an App with the Odoo Framework
 
How to lock a Python in a cage? Managing Python environment inside an R project
How to lock a Python in a cage?  Managing Python environment inside an R projectHow to lock a Python in a cage?  Managing Python environment inside an R project
How to lock a Python in a cage? Managing Python environment inside an R project
 
Bye bye $GLOBALS['TYPO3_DB']
Bye bye $GLOBALS['TYPO3_DB']Bye bye $GLOBALS['TYPO3_DB']
Bye bye $GLOBALS['TYPO3_DB']
 
Into The Box 2018 Ortus Keynote
Into The Box 2018 Ortus KeynoteInto The Box 2018 Ortus Keynote
Into The Box 2018 Ortus Keynote
 
Reactive Java Programming: A new Asynchronous Database Access API by Kuassi M...
Reactive Java Programming: A new Asynchronous Database Access API by Kuassi M...Reactive Java Programming: A new Asynchronous Database Access API by Kuassi M...
Reactive Java Programming: A new Asynchronous Database Access API by Kuassi M...
 
Recommendations for Building Machine Learning Software
Recommendations for Building Machine Learning SoftwareRecommendations for Building Machine Learning Software
Recommendations for Building Machine Learning Software
 

Plus de Odoo

Plus de Odoo (20)

Timesheet Workshop: The Timesheet App People Love!
Timesheet Workshop: The Timesheet App People Love!Timesheet Workshop: The Timesheet App People Love!
Timesheet Workshop: The Timesheet App People Love!
 
Keynote - Vision & Strategy
Keynote - Vision & StrategyKeynote - Vision & Strategy
Keynote - Vision & Strategy
 
Opening Keynote - Unveilling Odoo 14
Opening Keynote - Unveilling Odoo 14Opening Keynote - Unveilling Odoo 14
Opening Keynote - Unveilling Odoo 14
 
Extending Odoo with a Comprehensive Budgeting and Forecasting Capability
Extending Odoo with a Comprehensive Budgeting and Forecasting CapabilityExtending Odoo with a Comprehensive Budgeting and Forecasting Capability
Extending Odoo with a Comprehensive Budgeting and Forecasting Capability
 
Managing Multi-channel Selling with Odoo
Managing Multi-channel Selling with OdooManaging Multi-channel Selling with Odoo
Managing Multi-channel Selling with Odoo
 
Product Configurator: Advanced Use Case
Product Configurator: Advanced Use CaseProduct Configurator: Advanced Use Case
Product Configurator: Advanced Use Case
 
Accounting Automation: How Much Money We Saved and How?
Accounting Automation: How Much Money We Saved and How?Accounting Automation: How Much Money We Saved and How?
Accounting Automation: How Much Money We Saved and How?
 
Rock Your Logistics with Advanced Operations
Rock Your Logistics with Advanced OperationsRock Your Logistics with Advanced Operations
Rock Your Logistics with Advanced Operations
 
Transition from a cost to a flow-centric organization
Transition from a cost to a flow-centric organizationTransition from a cost to a flow-centric organization
Transition from a cost to a flow-centric organization
 
Synchronization: The Supply Chain Response to Overcome the Crisis
Synchronization: The Supply Chain Response to Overcome the CrisisSynchronization: The Supply Chain Response to Overcome the Crisis
Synchronization: The Supply Chain Response to Overcome the Crisis
 
Running a University with Odoo
Running a University with OdooRunning a University with Odoo
Running a University with Odoo
 
Down Payments on Purchase Orders in Odoo
Down Payments on Purchase Orders in OdooDown Payments on Purchase Orders in Odoo
Down Payments on Purchase Orders in Odoo
 
Odoo Implementation in Phases - Success Story of a Retail Chain 3Sach food
Odoo Implementation in Phases - Success Story of a Retail Chain 3Sach foodOdoo Implementation in Phases - Success Story of a Retail Chain 3Sach food
Odoo Implementation in Phases - Success Story of a Retail Chain 3Sach food
 
Migration from Salesforce to Odoo
Migration from Salesforce to OdooMigration from Salesforce to Odoo
Migration from Salesforce to Odoo
 
Preventing User Mistakes by Using Machine Learning
Preventing User Mistakes by Using Machine LearningPreventing User Mistakes by Using Machine Learning
Preventing User Mistakes by Using Machine Learning
 
Becoming an Odoo Expert: How to Prepare for the Certification
Becoming an Odoo Expert: How to Prepare for the Certification Becoming an Odoo Expert: How to Prepare for the Certification
Becoming an Odoo Expert: How to Prepare for the Certification
 
Instant Printing of any Odoo Report or Shipping Label
Instant Printing of any Odoo Report or Shipping LabelInstant Printing of any Odoo Report or Shipping Label
Instant Printing of any Odoo Report or Shipping Label
 
How Odoo helped an Organization Grow 3 Fold
How Odoo helped an Organization Grow 3 FoldHow Odoo helped an Organization Grow 3 Fold
How Odoo helped an Organization Grow 3 Fold
 
From Shopify to Odoo
From Shopify to OdooFrom Shopify to Odoo
From Shopify to Odoo
 
Digital Transformation at Old MacDonald Farms: A Personal Story
Digital Transformation at Old MacDonald Farms: A Personal StoryDigital Transformation at Old MacDonald Farms: A Personal Story
Digital Transformation at Old MacDonald Farms: A Personal Story
 

Dernier

Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...
Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...
Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...
lizamodels9
 
Insurers' journeys to build a mastery in the IoT usage
Insurers' journeys to build a mastery in the IoT usageInsurers' journeys to build a mastery in the IoT usage
Insurers' journeys to build a mastery in the IoT usage
Matteo Carbone
 
unwanted pregnancy Kit [+918133066128] Abortion Pills IN Dubai UAE Abudhabi
unwanted pregnancy Kit [+918133066128] Abortion Pills IN Dubai UAE Abudhabiunwanted pregnancy Kit [+918133066128] Abortion Pills IN Dubai UAE Abudhabi
unwanted pregnancy Kit [+918133066128] Abortion Pills IN Dubai UAE Abudhabi
Abortion pills in Kuwait Cytotec pills in Kuwait
 
Call Girls Jp Nagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Bang...
Call Girls Jp Nagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Bang...Call Girls Jp Nagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Bang...
Call Girls Jp Nagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Bang...
amitlee9823
 
Nelamangala Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Nelamangala Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...Nelamangala Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Nelamangala Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
amitlee9823
 
Call Girls in Delhi, Escort Service Available 24x7 in Delhi 959961-/-3876
Call Girls in Delhi, Escort Service Available 24x7 in Delhi 959961-/-3876Call Girls in Delhi, Escort Service Available 24x7 in Delhi 959961-/-3876
Call Girls in Delhi, Escort Service Available 24x7 in Delhi 959961-/-3876
dlhescort
 
FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756
dollysharma2066
 
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...
lizamodels9
 
Russian Call Girls In Gurgaon ❤️8448577510 ⊹Best Escorts Service In 24/7 Delh...
Russian Call Girls In Gurgaon ❤️8448577510 ⊹Best Escorts Service In 24/7 Delh...Russian Call Girls In Gurgaon ❤️8448577510 ⊹Best Escorts Service In 24/7 Delh...
Russian Call Girls In Gurgaon ❤️8448577510 ⊹Best Escorts Service In 24/7 Delh...
lizamodels9
 

Dernier (20)

Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...
Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...
Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...
 
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...
 
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptx
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptxB.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptx
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptx
 
(Anamika) VIP Call Girls Napur Call Now 8617697112 Napur Escorts 24x7
(Anamika) VIP Call Girls Napur Call Now 8617697112 Napur Escorts 24x7(Anamika) VIP Call Girls Napur Call Now 8617697112 Napur Escorts 24x7
(Anamika) VIP Call Girls Napur Call Now 8617697112 Napur Escorts 24x7
 
Insurers' journeys to build a mastery in the IoT usage
Insurers' journeys to build a mastery in the IoT usageInsurers' journeys to build a mastery in the IoT usage
Insurers' journeys to build a mastery in the IoT usage
 
Falcon Invoice Discounting platform in india
Falcon Invoice Discounting platform in indiaFalcon Invoice Discounting platform in india
Falcon Invoice Discounting platform in india
 
unwanted pregnancy Kit [+918133066128] Abortion Pills IN Dubai UAE Abudhabi
unwanted pregnancy Kit [+918133066128] Abortion Pills IN Dubai UAE Abudhabiunwanted pregnancy Kit [+918133066128] Abortion Pills IN Dubai UAE Abudhabi
unwanted pregnancy Kit [+918133066128] Abortion Pills IN Dubai UAE Abudhabi
 
Call Girls Jp Nagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Bang...
Call Girls Jp Nagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Bang...Call Girls Jp Nagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Bang...
Call Girls Jp Nagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Bang...
 
Mondelez State of Snacking and Future Trends 2023
Mondelez State of Snacking and Future Trends 2023Mondelez State of Snacking and Future Trends 2023
Mondelez State of Snacking and Future Trends 2023
 
Uneak White's Personal Brand Exploration Presentation
Uneak White's Personal Brand Exploration PresentationUneak White's Personal Brand Exploration Presentation
Uneak White's Personal Brand Exploration Presentation
 
Nelamangala Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Nelamangala Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...Nelamangala Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Nelamangala Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
 
Call Girls in Delhi, Escort Service Available 24x7 in Delhi 959961-/-3876
Call Girls in Delhi, Escort Service Available 24x7 in Delhi 959961-/-3876Call Girls in Delhi, Escort Service Available 24x7 in Delhi 959961-/-3876
Call Girls in Delhi, Escort Service Available 24x7 in Delhi 959961-/-3876
 
Falcon Invoice Discounting: The best investment platform in india for investors
Falcon Invoice Discounting: The best investment platform in india for investorsFalcon Invoice Discounting: The best investment platform in india for investors
Falcon Invoice Discounting: The best investment platform in india for investors
 
Dr. Admir Softic_ presentation_Green Club_ENG.pdf
Dr. Admir Softic_ presentation_Green Club_ENG.pdfDr. Admir Softic_ presentation_Green Club_ENG.pdf
Dr. Admir Softic_ presentation_Green Club_ENG.pdf
 
Business Model Canvas (BMC)- A new venture concept
Business Model Canvas (BMC)-  A new venture conceptBusiness Model Canvas (BMC)-  A new venture concept
Business Model Canvas (BMC)- A new venture concept
 
FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756
 
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...
 
Russian Call Girls In Gurgaon ❤️8448577510 ⊹Best Escorts Service In 24/7 Delh...
Russian Call Girls In Gurgaon ❤️8448577510 ⊹Best Escorts Service In 24/7 Delh...Russian Call Girls In Gurgaon ❤️8448577510 ⊹Best Escorts Service In 24/7 Delh...
Russian Call Girls In Gurgaon ❤️8448577510 ⊹Best Escorts Service In 24/7 Delh...
 
Famous Olympic Siblings from the 21st Century
Famous Olympic Siblings from the 21st CenturyFamous Olympic Siblings from the 21st Century
Famous Olympic Siblings from the 21st Century
 
Falcon's Invoice Discounting: Your Path to Prosperity
Falcon's Invoice Discounting: Your Path to ProsperityFalcon's Invoice Discounting: Your Path to Prosperity
Falcon's Invoice Discounting: Your Path to Prosperity
 

Discover GraphQL with Python, Graphene and Odoo

  • 1. Discover GraphQL with Python, Graphene and Odoo #OdooExperience 2019-10-03 Stéphane Bidoul <stephane.bidoul@acsone.eu> Version 1.0.0
  • 2. A short story • Why this talk… 2 / 46
  • 3. /me in a nutshell • @sbidoul • CTO of (https://acsone.eu) • Elected Board Member of (https://odoo-community.org) • Python since 1996 (1.4) • FLOSS, because… • Have used a lot of RPC mechanisms 3 / 46
  • 4. Content • What is GraphQL? • Demo • How to… for Odoo with Graphene • How is GraphQL different? • Caveats and thoughts • Resources • Q&A 4 / 46
  • 5. What is GraphQL? • Yet another Remote Procedure Call protocol? • Open Sourced by Facebook in 2015 • Basic characteristics • Requests: GraphQL data query language • Responses: json • Schema: GraphQL schema language • Transport: usually HTTPS (GET, POST) • Variety of server side libs, no need for client side lib 5 / 46
  • 6. Demo • GraphQL Schema for Odoo Partners and Contacts. 6 / 46
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24. How to… for Odoo with Graphene import graphene class Country(graphene.ObjectType): code = graphene.String(required=True) name = graphene.String(required=True) 24 / 46
  • 25. How to… for Odoo with Graphene from odoo.addons.graphql_base import OdooObjectType class Partner(OdooObjectType): name = graphene.String(required=True) street = graphene.String() street2 = graphene.String() city = graphene.String() zip = graphene.String() email = graphene.String() phone = graphene.String() is_company = graphene.Boolean(required=True) # ... 25 / 46
  • 26. How to… for Odoo with Graphene class Partner(OdooObjectType): # ... country = graphene.Field(Country) @staticmethod def resolve_country(root, info): return root.country_id or None 26 / 46
  • 27. How to… for Odoo with Graphene class Partner(OdooObjectType): # ... contacts = graphene.List( graphene.NonNull(lambda: Partner), required=True, ) def resolve_contacts(root, info): return root.child_ids 27 / 46
  • 28. How to… for Odoo with Graphene class Query(graphene.ObjectType): all_partners = graphene.List( graphene.NonNull(Partner), required=True, companies_only=graphene.Boolean(), limit=graphene.Int(), offset=graphene.Int(), ) # ... 28 / 46
  • 29. How to… for Odoo with Graphene class Query(graphene.ObjectType): # ... def resolve_all_partners( root, info, companies_only=False, limit=limit, offset=offset ): # ... check for max limit domain = [] if companies_only: domain.append(("is_company", "=", True)) ResPartner = info.context["env"]["res.partner"] return ResPartner.search(domain, limit=limit, offset=offset) 29 / 46
  • 30. How to… for Odoo with Graphene schema = graphene.Schema(query=Query) 30 / 46
  • 31. How to… for Odoo with Graphene from odoo import http from odoo.addons.graphql_base import GraphQLControllerMixin from ..schema import schema class GraphQLController(http.Controller, GraphQLControllerMixin): @http.route("/graphiql/demo", auth="user") # GraphiQL IDE def graphiql(self, **kwargs): return self._handle_graphiql_request(schema) @http.route("/graphql/demo", auth="user") def graphql(self, **kwargs): return self._handle_graphql_request(schema) 31 / 46
  • 32. How is GraphQL different? A long ancestry • ASN.1, DCOM, CORBA, SOAP, REST+OpenAPI and many more • Some sort of schema language • Schema is machine readable (eg for automatic message validation) • “On the wire” representation of corresponding messages • Rigid request/response data structures • The service developer interprets and validates the request, does stuff, and prepares the response 32 / 46
  • 33. How is GraphQL different? What about SQL? • Machine readable schema • “On the wire” message representation is proprietary (database “drivers” instead) • Flexible queries, written by the client developer • There is no service developer, the database does it (stored procedures fall in previous category) 33 / 46
  • 34. How is GraphQL different? • Client-side freedom of SQL. • Server-side freedom of REST. 34 / 46
  • 35. Caveats and thoughts: a better REST? • What is REST? • REST + OpenAPI • Crafting a pure REST API is an art that few master • GraphQL breaks HTTP semantics • Little leverage of HTTP infrastructure (caching, firewalls, etc) • With pure REST it’s “easy”, see above • Attention to wild clients, complex queries • As always, it’s a matter of tradeoffs 35 / 46
  • 36. Caveats and thoughts: Performance Beware of naive implementation of resolvers! DON’T (one database query per returned record): def resolve_contacts(root, info): ResPartner = info.context["env"]["res.partner"] return ResPartner.search([('parent_id', '=', root.id)]) DO (use ORM prefetching strategies): def resolve_contacts(root, info): return root.child_ids 36 / 46
  • 37. Caveats and thoughts: Façadism • Temptation to expose all your domain model? • Easy with generic GraphQL adapters (Django, SQLAlchemy, …) • Should be quite easy for Odoo too • It depends on the use case • Often better to create a façade dedicated to the client use cases • Don’t expose your guts and break clients when your domain model changes 37 / 46
  • 38. Caveats and thoughts: Access Control • With traditional RPC (eg REST), access control is typically done at the façade/service level • GraphQL typically binds at the domain model level • Built-in security in your domain model or data sources? 38 / 46
  • 39. Key takeaways • GraphQL is easier than it sounds, try it! • Powerful alternative to REST • Very easy to integrate in any Python web application thanks to Graphene • High productivity for backend devs • High flexibility to frontend devs 39 / 46
  • 40. Resources • Start here • https://graphql.org/learn/ • With Python • https://graphene-python.org/ • Incl. support for different frameworks (eg Django, SQLAlchemy) • With Odoo • https://pypi.org/project/odoo12-addon-graphql-base/ • https://pypi.org/project/odoo12-addon-graphql-demo/ 40 / 46