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.
Related
I am new to Flask. I am making this call to this particular api but I am getting error which i am not able to solve after much searching also..because everytime i solve it..it pops some new error. This api should return json data but i think something is wrong with my syntax. Can anyone help me with this.
from flask.json import jsonify
from flask.templating import render_template
import requests
import json
app = Flask(__name__)
#app.route("/")
def get_data():
url = "http://api.tvmaze.com/search/shows?q=girls"
data = requests.get(url)
return data.json()
if __name__ == "__main__":
app.run(debug = True, port = 3000)
As you mensioned in comments, the problem in that you are trying to give list as response object. Flask can't do it. So, you should try to use json module like this:
urlist = [1, 2, 3, 4, 5]
dumped_json = json.dumps(urlist)
Output:
>>> type(json.dumps(dumped_json))
<class 'str'>
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
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
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
I am using this code and i am using url=http://money.moneygram.com.au/forex-tools/currency-converter-widget-part
from __future__ import absolute_import
#import __init__
#from scrapy.spider import BaseSpider
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.http import Request
from scrapy.http import FormRequest
from scrapy.http import Response
from scrapy.selector import HtmlXPathSelector
import MySQLdb
class DmozSpider(CrawlSpider):
name = "moneygram"
allowed_domains = ["moneygram.com"]
start_urls = ["http://money.moneygram.com.au/forex-tools/currency-converter-widget-part"]
def parse(self,response):
# yield FormRequest.from_response(response,formname='firstSelector',formdata="FromCurrency=USD&ToCurrency=INR&FromCurrency_dropDown=USD&ToCurrency_dropDown=INR",callback=self.parse1)
# request_with_cookies = Request(url="http://money.moneygram.com.au",
# cookies={'FromCurrency': 'USD', 'ToCurrency': 'INR'},callback=self.parse1)
yield FormRequest.from_response(response,formname=None,formnumber=0,formpath=None,formdata="FromCurrency=AED&ToCurrency=VND&FromCurrency_dropDown=AED&ToCurrency_dropDown=VND&FromAmount=2561&ToAmount=&X-Requested-With=XMLHttpRequest",callback=self.parse1)
To send the form data as required to me but is giving error that
raise ValueError("No <form> element found in %s" % response)
exceptions.ValueError: No <form> element found in <200 http://money.moneygram.com.au/forex-tools/currency-converter-widget-part>
How can I convert from usd to inr ?
The page you mentioned is not a valid HTML. Looks it's a SSI block which should be part of another page.
You the error because This page uses Javascript heavily. It doesn't have a
FormRequest.from_response tries to make the request using an existing form, but the form is not there.
You should either work with the whole page, or make up the FormRequest filling it's attributes manually and then submitting it to the URL from the whole page.