How can I create GraphQL API's with Django and Neo4j Database? - python

I am working on a project where I need to make GraphQL API's with Django Server (Graphene-Django) and Neo4J database. I have looked quite a lot over the internet, but I wasn't able to find any useful resources. If anyone can give a simple example of the flow or suggest some resources, please help.

I worked with all 3 of the stacks:
Graphene-Django with Postgresql DB
Django with Neo4j & Postgresql
Neo4j
I can tell you actually you can have either one or the other.
Neo4j has it's own web interface and it's own GraphQL API Built in:
http://yourhost:7474/browser/
http://yourhost:7474/api/
For Django to work with Neo4j you can use neomodel or even better the django version of it: django-neomodel that is using neomodel under the hood.
I am actually having a separate setup and I use Django REST Framework and everything I store in Neo4j i expose it in REST endpoints instead of GraphQL.
So I would say you can either Use django-neomodel to manage/work with your data and you can simply decide if you want to:
use Graphene-Django to expose all of the data Neo4j included
use Neo4j GraphQL API
One thing though...I would still advice you to have a DEFAULT_DATABASE one of the Officially supported to handle User related data and authentication.
As a personal remark: Neo4j is a great technology but is not the fastest when it comes to transaction speed (where Postgres or other relational databases shines).
It is after all a technology running on Java and not on C++ like most of the other Databases out there...so keep that in mind.
Good luck.

I'm running a similar setup, but you're talking about a lot of things here, it might be easier to understand if you break up the concepts.
It's easiest to understand if you think about just running Neo4j in Python (independent of Django).
Neo4j/Python
Get your Neo4j running and be able to connect to it using python (I use py2neo).
I made a video demo of making neo4j flask app starting here: https://www.youtube.com/watch?v=h8cyPIEfxQY&t=1215s
Code for this is here: https://github.com/elena/graph-fun/blob/master/notebook.ipynb
Django/Graphene
Get your Django project running. Setup graphene in Django (note, wrapping your head around graphene/graphQL is a whole other thing, but do this step separately, ensure you understand how your conventional Django app can connect to graphene).
Some magic sauce here is that we use GraphiQL to serve GraphQL endpoints: https://github.com/graphql/graphiql this generally makes your life much easier.
These docs: https://www.fullstacklabs.co/blog/django-graphene-rest-graphql
Python/Graphene/Neo4j
Make a module/app in your Django project for your Neo4j connection and statements. Important to note here is: graphene doesn't care where the data comes from. Just use plain python-graphene to send whatever data to graphene schema.py
This is the flask example code (https://github.com/elena/graph-fun/blob/master/app.py), but you can just feed the Neo4j output to your GraphQL python schema.
See, python (not Django) Graphene doesn't care where data comes from: https://docs.graphene-python.org/en/latest/quickstart/
Finally you can wrap it all up in your django urls to serve using graphiql.
--
So you need django-graphene to server your schema.py/urls, but this overcomplicates things.
You then need to take a step back and use naive python-graphene to serve Neo4j.
At least that's what works for me.

Related

Is it possible to use 2 different frameworks in 1 backend of a web app?

I am an 11th grade student and I'm learning how to build a web app, with my teammates. Currently, We're making a website showing the school schedule (also to show students' marks) and helping the users to create their to-do lists, of course this web serves students like me. In the backend of the web, we use Python as the main language, Flask as the framework and MySQL to manipulate our database. Now, everything is ok and we're trying to make something like an admin interface for people who host the web. Specifically, it is where teachers can insert their students' grade, and maybe adjust the school timetable. The problem is, we're learning how to use Flask Admin to code that function, and we've found out this tech is only compatible with SQL Server. However, we have a better understand in MySQL therefore we could create multiple tasks, in contrast, we don't know how to use SQL Server to create those funcs. Now I have 2 main questions:
Could we use 2 different SQL in the backend of our web? It is the quickest way we know, however we have to learn how to use SQL Server.
Could we use 2 different Python backend frameworks in the backend of our web? We haven't searched which framework to use yet because we don't know if it's possible to do this.
We don't know any other ways to solve this problem except getting rid of MySQL and use SQL Server instead. However this is not the way we prefer and we hope those 2 questions answered. If there is anything wrong in our knowledge please just straightly comment to let us know, and we greatly welcome any other solutions. Thanks for answering!!
Directly from the flask-admin docs https://flask-admin.readthedocs.io/en/latest/advanced/#using-different-database-backends is the following:
Using Different Database Backends Other than SQLAlchemy… There are
five different backends for you to choose from, depending on which
database you would like to use for your application. If, however, you
need to implement your own database backend, have a look at Adding A
Model Backend.
If you don’t know where to start, but you’re familiar with relational
databases, then you should probably look at using SQLAlchemy. It
is a full-featured toolkit, with support for SQLite, PostgreSQL,
MySQL, Oracle and MS-SQL amongst others. It really comes into its own once you have lots of data, and a fair amount of relations between
your data models. If you want to track spatial data like
latitude/longitude points, you should look into GeoAlchemy, as well.
Regarding the original question, it is possible to use two different frameworks in the backend of a web app. One way to do so would be to set up a reverse proxy server (see https://www.nginx.com/resources/glossary/reverse-proxy-server/#:~:text=A%20reverse%20proxy%20server%20is,traffic%20between%20clients%20and%20servers.), but I would recommend giving SQLAlchemy before doing so.
Why do you think that flask-admin is tied to SqlServer? Flask (and flask-admin) can handle different connections to various databases:
https://github.com/flask-admin/flask-admin#introduction
https://flask-admin.readthedocs.io/en/v1.0.9/db/
My guess is you are currently using SqlAlchemy. As explained here, you can use different backends:
The string form of the URL is dialect[+driver]://user:password#host/dbname[?key=value..], where dialect is a database name such as mysql, oracle, postgresql, etc., and driver the name of a DBAPI, such as psycopg2, pyodbc, cx_oracle, etc.
Alternatively, the URL can be an instance of URL.
(https://docs.sqlalchemy.org/en/13/core/engines.html#sqlalchemy.create_engine)
More on Engine here
Flask-admin is a admin view on your database tables - you cannot run it on a "different" db then the tables it should modify. It needs to have access to the database tables you want it to modify, so you cannot run "admin" on MS and "your data backend" on another database(-connection).
Some other things to think about:
MS-(T-)Sql and MySql are infrastructural choices, language wise they are very closely related so adapting MySql knowledge to T-SQL Syntax should be possible. Choosing SqlServer may force you to license it - and afaik that comes with fees (eiter on premise or as a azure subscription wich might or might not be free for schools (no idea - but you should check that)).
This sounds like an ambitious project for school - depending on where you live, privat data protection laws come into play especially considering you connect names with schedules with grades which would need you to implement a lot more to comply.
For first question, I checked flask-admin documentation and found that the framework already included serval built-in ORM library, i.e. SQLAlchemy, MongoEngine, pymongo and Peewee. This means you can just directly import the ORM library from the flask-admin package and use it to access your database. For your case, you should look for SQLAlchemy as you are using SQL Database. Both SQL Server and MySQL are supported by SQLAlchemy.
The Adding Model Views section in their official doc also mentioned it as well:
https://flask-admin.readthedocs.io/en/latest/introduction/#getting-started
For the second question, it is technically not possible to apply two different frameworks in one single backend application.

How to generate complex ORM code and REST API with swagger-codegen?

swagger-editor is with codegen tool built in, so I can generate server side code with it. I try the pet store example, and it works. Then my next try is to think about data persistence. I google around, and I often use Python/Java, so I focus on this 2 languages.
First I would like to try python.
In the swagger-codegen tool, it depends on flask/connexion/flask-swagg and so on, so I think connexion is a good start for me. However when I read the generated code, I found that swagger-codegen inherits swagger data Model itself, and I can use connexion with SQLAlchemy to implement db ORM. For example
Connexion-Example. Also I found SAFRS a good place to go, with this I can easily expose all the DB models as REST API, so that I don't need to create duplicate ORM code myself. So I try to find some suggestions, which can help me out, because now I am stuck.
I want to create a API specification file(yaml or json in swagger-editor), and also the DB model. Then generate server side code, including DB model with SQLAlchemy, with all the DB CRUD ops as REST API. My first thinking is to modify swagger template in swagger-codegen, to use SAFRS or connexion. But I would like to discuss here to get some advise on how you manage to do this kind of work?
Thanks.
Andes

How to query MySQL database using API in python?

I have my data in database, and I want to build an API using python to query the database. What do I use or where do I even start ?
I can connect to my database and pull the data. But I do not know how to build an API for other users to query the database
NOT a trivial solution, but worth looking into, depending on how big a project this is and what else you may want to do with Python and MySQL.
Django is a framework for Python that can handle a lot of things but, most importantly, provides a very powerful interface to MySQL and other databases.
One of the many add-ons for Django is Django REST Framework which is specifically designed for setting up Restful APIs using Django & Python.
I have used Django & Django REST Framework extensively. It can take a while to get up to speed, but I think still a lot less work than if you were to take a basic connector between Python & MySQL (having to code SQL statements manually) and code the API interface at a lower level (Django REST Framework isn't perfect but it takes care of a lot of the details).

Django Admin using RESTful API v.s. Database

This is a bit of a strange question, I know, but bear with me. We've developed a RESTful platform using Python for one of our iPhone apps. The webapp version has been built using Django, which makes use of this API as well. We were thinking it would be a great idea to use Django's built-in control panel capabilities to help manage the data.
This itself isn't the issue. The problem is that everyone has decided it would be best of the admin center was essentially a client that sits on top of the RESTful platform.
So, my question is, is there a way to manipulate the model layer of Django to access our API directly, rather than communicated directly with the database? The model layer would act as the client passing requests and responses to and from the admin center.
I'm sure this is possible, but I'm not so sure as to where I would start. Any input?
I remember I once thought about doing such thing. At the time, I created a custom Manager using a custom QuerySet. And I overrode some methods such as _filter_or_exclude(), count(), exists(), select_related(), ... and added some properties. It took less than a week to become a total mess that had probably no chance to work one day. So I immediately stopped everything and found a more suitable solution.
If I had to do it once again, I would take a long time to consider alternatives. And if it really sounds like the best thing to do, I'd probably create a custom database backend. This backend would, rather than converting Django ORM queries to SQL queries, convert them to HTTP requests.
To do so, I think the best starting point would be to get familiar with django source code concerning database backends.
I also think there are some important things to consider before starting such development:
Is the API able to handle any Django ORM request? Put another way: Will any Django ORM query be translatable to an API request?
If not, may "untranslatable" queries be safely ignored? For instance, an ORDER BY clause might be safe to ignore. While a GROUP BY clause is very unlikely to be safely dismissed.
If some queries can't be neither translated nor ignored, may them be reasonably emulated. For instance, if your API does not support a COUNT() operation, you could emulate it by getting the whole data and count it in python with len(), but is this reasonable?
If they are still some queries that you won't be able to handle (which is more than likely): Are all "common" queries (in this case, all queries potentially used by Django Admin) covered and will it be possible to upgrade the API if an uncovered case is discovered lately or is introduced in a future version of Django?
According to the use case, there are probably tons of other considerations to take, such as:
the integrity of the data
support of transactions
the timing of a query which will be probably much higher than just querying a local (or even remote) database.

Choosing the right database system for a Django web application

I am currently in the planning stages of building a simple Django web app (for learning proposes). Basically, teacher’s can login, input student grades, and then the students can login and view their grades. Each class has a group number.
Here is a template of a user:
Username: Johny098
Password: Y98uj*?877!(
Name: John Doe
Gender: Male
Group: 32
Secondary: 5
Taking into consideration that I am starting with django and web developpement in general, I find confusing the number of database systems that are available to me: MySQL, CouchDB, MongoDB, SQLite, etc. And I am having a hard time deciding which database system to use for my purpose (I have no prior experience with databases).
After some research I found Couchdb (and SQLite) which seems fairly simple to pick up and fun to use, but that's just me, and that's why I need help. I know there are numerous debates on SQL vs NoSQL, but I don't really know if this will have an impact for my use of the databases. Ideally, the database system should integrate well with django and be easy enough to pick up in a couple of days.
So, coming back to the question: What database system should I use for my web app?
Any resources would also be appreciated.
Thanks,
-Raphael
For learning purposes I'd recommend SQLite: no setup, no background daemons running, everything is bundled with Python, it's SQL (so it maps well with Django ORM), and it's a very simple DBMS. In fact, some people use SQLite for prototyping and then switch to MySQL/PostgreSQL in production.
As for NoSQL, I would not recommend to use it unless you know exactly why and for what purpose you need it.
Oh, and one last thing: store password hashes (md5 or sha1), not the raw passwords. It's not necessary in your case, but in real-world apps it's mandatory.
The Django website has a page that lists the database backends supported. However, Django's database access layer is designed to work more or less the same no matter which database backend you're using. There are some differences described on the page I linked, but they shouldn't come up in normal usage if you're writing just a basic web app. So as far as effects on how you write your web app, among the choices listed it really doesn't matter.
Note that all the database backends Django supports are SQL-based, I believe. Accessing the database through Django does eliminate some of the security issues that I believe prompted the NoSQL movement... in any case, NoSQL is something you can pretty much ignore for now.
In your case, I would suggest picking SQLite, simply because it's easier to set up, and you don't want to spend time worrying about how to configure the database when you should be worrying about how to build your web app. The difference between SQLite and most other DBMSs (database management systems) is that SQLite stores each database in a regular file, and the SQLite client works directly with that file. Other DBMSs (like MySQL, PostgreSQL, Oracle, etc.) have a central location for the databases, a server to manage them, and a client that connects to the server and handles all the database access. A server-based DBMS works well for a busy web app, because it has features to handle many simultaneous requests to the database, but since you're just using this as a learning project, you don't need those features.
I would go for MySQL ... why? because among the ones you named, it is the most popular and, better than that, it will give you more credit when looking for a job (for instance, you can go to monster dot com and find how many jabs require you to know MySQL vs how many SQL-Lite).
Also, MySQL is simple and easy to learn, there are many GUI clients (some of which are Open Source) and it has pretty good documentation.

Categories