Create neo4j graph database from python using html forms - html

Hi i'm very new to neo4j i need to know how to create nodes and properties of graph using html forms by using py2neo and neo4j and how to add auto id's to the nodes
from flask import Flask,render_template,request,url_for,json,jsonify
from py2neo import neo4j,Graph,Node,Relationship,cypher
from neo4jrestclient.client import GraphDatabase
app = Flask(__name__)
gdb = GraphDatabase("http://neo4j:duke#localhost:7474/db/data")
graph=Graph("http://neo4j:duke#localhost:7474/db/data")
#app.route('/')
def index():
results = graph.cypher.execute("MATCH (n:Person) RETURN n")
'''print "gyktdjxdhgfcvkjbljkfr",result'''
return results.json
#app.route('/hello')
def create():
return "f"
if __name__ == '__main__':
app.run()

Check out this blog post by Nicole for some insight:
http://neo4j.com/blog/building-python-web-application-using-flask-neo4j/
code is on github:
https://github.com/nicolewhite/neo4j-flask
You don't need auto-incrementing id's like in a relational database.
Just use the person's login for that and use MERGE
See. http://neo4j.com/developer/cypher

Related

Using flask_excel within Blueprints

I have an application that is using Blueprints and I need to be able to generate csv files for download. I found the flask_excel package which works great, but none of the examples I've found use Blueprints. Here is an example application that works:
#app.py
from flask import Flask
import flask_excel as excel
app=Flask(__name__)
excel.init_excel(app)
#app.route("/example", methods=['GET'])
def example():
return excel.make_response_from_array([[1,2], [3, 4]], "csv", file_name="example_data")
if __name__ == "__main__":
app.run()
However, I need something structured like this:
#__init__.py
from flask import Flask
import flask_excel as excel
from download_csv import download_csv_bp
def create_app():
app = Flask(__name__)
app.register_blueprint(download_csv_bp)
excel.init_excel(app)
return app
app = create_app()
and
#download_csv.py
from flask import Flask, Blueprint
download_csv_bp=Blueprint('download_csv',__name__)
#download_csv_bp.route("/example", methods=['GET'])
def example():
return excel.make_response_from_array([[1,2], [3, 4]], "csv", file_name="example_data")
How do I import the flask_excel functions that are initialized in __init__.py? If I put import flask_excel as excel in my download_csv.py file, the response generated just prints the resulting text to the screen.
The solution was simpler than I thought. If I add the line from app import excel to download_csv.py then it works. My new issue is with ajax calling this route, but as this is unrelated to my original question, I won't ask it here.

How to preprocess the new dataset while model deployement using flask

data = dataset.iloc[:,:-1].values
label = dataset.iloc[:,-1].values
from sklearn.preprocessing import LabelEncoder
labelencoder = LabelEncoder()
for i in range(0,5):
data[:,i] = labelencoder.fit_transform(data[:,i])
data1=pd.DataFrame(data[:,:5])
for i in range(7,12):
data[:,i]=labelencoder.fit_transform(data[:,i])
data2=pd.DataFrame(data[:,7:12])
from sklearn.preprocessing import Normalizer
#----Normalizing Uncategorical Data----#
data3=dataset.iloc[:,[5,6,12]]
dataset.iloc[:,:5]
normalized_data = Normalizer().fit_transform(data3)
data3=pd.DataFrame(normalized_data)
data_full=pd.concat([data1,data2,data3],axis=1)
label=labelencoder.fit_transform(label)
label=pd.DataFrame(label)
Above are my preprocessing steps...the same i want to do to new input data after model deployment through web app.
How to write a function for this..?
i am using flask for developing apis
What to write under predict fund...? in app.py
#app.route('/predict' methods= 'POST' )
def predict():
You will have to pickle all the transformers that you are using while pre-processing your data. Then you will have to load the same transformers and use them during predictions.
Creating a new transformer and fitting it on different value will give your weird predictions.
I created a demo flask project for a meetup. It has all the code that you need.
Deployment: https://github.com/Ankur-singh/flask_demo/blob/master/final_ml_flask.py
Training: https://github.com/Ankur-singh/flask_demo/blob/master/iris.py

How can I process json file and display some data in form of charts in django

Basically, I have implemented Sentiment analysis for the Amazon review dataset in python. Now I want to make a web app for it. I try to look on google for it but all the projects are for Twitter data. Till now I make a Django app which can take json file from the user and display the success message. Any ideas on how to load the json file in my script and put these data on the charts
Create a model to upload the file. Create a director upload for uploading at root of your project
from django.db import models
class JSONFile(models.Model):
file = models.FileField(upload_to='uploads')
You can use a form:
from django import forms
class JSONFileForm(forms.Form):
file = forms.FileField(
label='Select a file',
help_text='max. 42 megabytes'
)
Create templates as 'chart.html' to show your chart accordingly and 'upload.html' to render above form
In your views.py:
from forms import JSONFileForm
from models import JSONFile
from django.shortcuts import render
def chart(request):
if request.method == 'POST':
form = JSONFileForm(request.POST, request.FILES)
if form.is_valid():
newfile = JSONFile(file = request.FILES['file'])
newfile.save()
json.dumps(request.FILES['file'])
#format your data here
return render(request,"chart.html",{}) #pass data context in {} as dict
else:
form = JSONFileForm(request.POST)
else:
form = JSONFileForm()
return render(request,"upload.html",{"form":form})

How to save a django model into json file

I would like to save a Django model into a json file into a specific directory. How can I do that? My code is below in views.py.
def JSON(request):
with open(r'C:\Users\Savas\Desktop\DOCUMENTS\file.json', "w") as out:
mast_point = serializers.serialize("json", Poi.objects.all())
out.write(mast_point)
Good morning!
did you look at the documentation for this? :)
Additionally i would suggest that you indent you code like the following:
from django.core import serializers
from .models import yourmodel
from django.http import HttpResponse
def example(request):
objects = yourmodel.objects.all()
with open(r'...your path...\file.json', "w") as out:
mast_point = serializers.serialize("json", objects)
out.write(mast_point)
template = loader.get_template('some_template.html')
context = {'object': objects}
return HttpResponse(template.render(context, request))
I just tried this code snippet and it worked in my sample django application, of course you have to adapt this snippet a little bit :)
As of version 1.1 and greater, the Django dumpdata management command allows you to dump data from individual tables:
./manage.py dumpdata myapp2.my_model > fixtures/file_name.json

Django Rest Framework: Retrieving object count from a model

Does anyone know how can I successfully retrieve the object count of a model, in JSON format, and how I need to configure my routing? I'm trying to achieve this using a APIView and returning a Response formatted by JSONRenderer.
UPDATE:
#api_view(['GET'])
#renderer_classes((JSONRenderer, JSONPRenderer))
def InfluenciasCountView(request, format=None):
influencia_count = Influencia.objects.count()
content = {'influencia_count': influencia_count}
return Response(content)
Here's the route I'm using:
url(r'^influencias/count/$', views.InfluenciasCountView, name='influencias-count')
Check out this snippet of code (the second one). If this does not suit your need, please add some of your code (for better understanding).
UPDATE
For routing, DRF offers a default router for each view. This means that you can have the following configuration in your urls.py: (using the example from the previous link)
url(r'^users/count/$', views. UserCountView.as_view(), name='users-count')
Then, when you access the URL your_base_url/users/count/ you will see something like {'user_count': 10}.
UPDATE 2
The entire code should look like this:
class UserCountView(APIView):
"""
A view that returns the count of active users.
"""
renderer_classes = (JSONRenderer, )
def get(self, request, format=None):
user_count = User.objects.count()
content = {'user_count': user_count}
return Response(content)
I am using routers from REST Framework to build my URLs. I tried above code but doesn't get it working. One of the problems is I cannot get /count/ into the router endpoints.
I checked DRF document (3.8.2) and found that there is a (new?) #action decorator (I was using 3.7.7 and it doesn't have it). So, here is my full solutions:
Upgrade DRF to 3.8.2 (or above) in requirements.txt (or PipFile if you using that).
Add a new action count method to the ModelViewSet
Update get_permissions to include the newly added action count
Here is my views.py:
from rest_framework.decorators import action
from rest_framework.response import Response
class PostViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows recommend to be viewed or edited.
"""
model = Post
queryset = Post.objects.filter(is_active=True)
serializer_class = serializers.PostSerializer
filter_backends = (filters.SearchFilter, DjangoFilterBackend,)
search_fields = ('title', 'body',)
filter_fields = ('status', 'type')
def get_permissions(self):
if self.action in ('list', 'retrieve', 'create', 'count'):
return (AllowAny()),
if self.action in ('update', 'partial_update'):
return (IsAdminUser()),
return (IsAdminUser()),
#action(detail=False)
def count(self, request):
queryset = self.filter_queryset(self.get_queryset())
count = queryset.count()
content = {'count': count}
return Response(content)
To query count of posts: /api/posts/count/?format=json
To query count of published: /api/posts/count/?format=json&status=published
One of the important thing here is to use the queryset from filter_queryset(...), rather than Post.objects.all().
UPDATE
Since count is common, I created a mixin for that.
from rest_framework.decorators import action
from rest_framework.response import Response
class CountModelMixin(object):
"""
Count a queryset.
"""
#action(detail=False)
def count(self, request, *args, **kwargs):
queryset = self.filter_queryset(self.get_queryset())
content = {'count': queryset.count()}
return Response(content)
To use it, just add CountModelMixin to your ModelViewSet (also support nested ModelViewSet).
class PostViewSet(viewsets.ModelViewSet, CountModelMixin):
If you use permissions, also add 'count' to the list of granted action.