Running the script gives below error :
AttributeError: module 'requests' has no attribute 'files'
Code is as follows :
import requests
app = Flask(__name__)
#app.route('/api/test/', methods=['POST'])
def test():
filesReceived = requests.files['file']
What I understand from your code, you are trying to get the file received by the request, right?
If that's what you want, you are using the wrong import.
Requests is an http library for python.
If you want the file sent in the request, you need to use request from flask.
So your code will be something like:
from flask import request
app = Flask(__name__)
#app.route('/api/test/', methods=['POST'])
def test():
filesReceived = request.files['file']
Related
I am attempting to create a Flask middleware in order to make py2neo transactions atomic. First I got a working outside of application context error, and I tried to apply this solution, as seen in the following code:
from flask import g
from py2neo import Graph
def get_db():
return Graph(password="secret")
class TransactionMiddleware(object):
def __init__(self, app):
self.app = app
with app.app_context(): # Error raises here.
g.graph = get_db()
g.transaction = g.graph.begin()
def __call__(self, environ, start_response):
try:
app_status = self.app(environ, start_response)
# some code
return app_status
except BaseException:
g.transaction.rollback()
raise
else:
g.transaction.commit()
But I got this error: AttributeError: 'function' object has no attribute 'app_context'.
I don't know if the solution I'm trying is not suitable for my case, or what is the problem.
You are in a WSGI middleware, so what gets passed in as an app is actually a method called Flask.wsgi_app the results of which you a later supposed to return from your __call__ handler.
Perhaps you can simply import your actual flask app and use app_context on that, as in:
from app import app # or whatever module it's in
# and then
class TransactionMiddleware(object):
...
def __call__(self, environ, start_response):
with app.app_context():
...
I would also consider just instantiating your Graph somehere on a module level. Perhaps next to your flask app instantiation and not attaching it to g. This way you can use it without application context:
# app.py
flask = Flask(__main__)
db = Graph(password="secret")
You can use it by directly importing:
# middleware.py
from app import db
I am making an api which return the JsonResponse as my text from the scrapy. When i run the scripts individually it runs perfectly. But when i try to integrate the scrapy script with python django i am not getting the output.
What i want is only return the response to the request(which in my case is POSTMAN POST request.
Here is the code which i am trying
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
import scrapy
from scrapy.crawler import CrawlerProcess
#csrf_exempt
def some_view(request, username):
process = CrawlerProcess({
'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)',
'LOG_ENABLED': 'false'
})
process_test = process.crawl(QuotesSpider)
process.start()
return JsonResponse({'return': process_test})
class QuotesSpider(scrapy.Spider):
name = "quotes"
def start_requests(self):
urls = [
'http://quotes.toscrape.com/random',
]
for url in urls:
yield scrapy.Request(url=url, callback=self.parse)
def parse(self, response):
return response.css('.text::text').extract_first()
I am very new to python and django stuff.Any kind of help would be much appreciated.
In your code, process_test is a CrawlerProcess, not the output from the crawling.
You need additional configuration to make your spider store its output "somewhere". See this SO Q&A about writing a custom pipeline.
If you just want to synchronously retrieve and parse a single page, you may be better off using requests to retrieve the page, and parsel to parse it.
I am trying to add a custom error code to a flask_restful API, following the directions given in the docs however I do not receive the correct response and I am getting a NameError: global name 'UnsupportedMediaType' is not defined message. What am I doing wrong here?
# -*- coding: utf-8 -*-
from flask import Flask, request
from flask_restful import Resource, Api
import service
errors = {
'UnsupportedMediaType': {
'message': 'Unsupported Media Type',
'status': 415
}
}
app = Flask(__name__)
api = Api(app, errors=errors)
class Service(Resource):
def post(self):
if request.is_json:
data = request.get_json()
return service.handler(args['data'])
else:
raise UnsupportedMediaType
api.add_resource(Service, '/')
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True)
You must store the error handler to a function. Like this:
def error(exception):
return {some json error data with the message 'exception'}
now you can call the error handler as you want.
OR
You can use Flask error handler decorator for that. Heres the link
I'm using Python 2.7, webapp2 and GAE for developing a web app.
I'm facing a problem which i don't understand, since I know what it means but everything I did seems correct.
I get the error
AttributeError: type object 'DeleteAccount' has no attribute 'DAccount'
when i try to access the URL myappdomain/DeleteAccount/
I imported in the main file the python file DeleteAccount.py
import DeleteAccount
I linked the URL with the relative class DAccount of DeleteAccount
webapp2.Route(r'/DeleteAccount/',DeleteAccount.DAccount)
That's my DeleteAccount.py file
import logging
import webapp2
from webapp2_extras import sessions
import datastore
import FBLogin
class BaseHandler(webapp2.RequestHandler):
def dispatch(self):
self.session_store = sessions.get_store(request=self.request)
try:
webapp2.RequestHandler.dispatch(self)
finally:
self.session_store.save_sessions(self.response)
#webapp2.cached_property
def session(self):
return self.session_store.get_session()
class DAccount(BaseHandler):
def get(self):
w = self.response.write
logging.info("deleting account")
w('I've deleted the account')
What's wrong? I did what I've done with every other module and everything has worked well with them
I have the following three files.
app.py
from flask_restful import Api
from lib import globals
from flask import Flask
from flask.ext.cache import Cache
globals.algos_app = Flask(__name__)
#cache in file system
globals.cache = Cache(globals.algos_app, config={'CACHE_TYPE': 'filesystem', 'CACHE_DIR': '/tmp'})
api = Api(globals.algos_app)
api.add_resource(Test, '/test')
if __name__ == '__main__':
globals.algos_app.run(host='0.0.0.0', debug=True)
globals.py
global algos_app
global cache
Test.py
from flask_restful import Resource
from lib import globals
from flask_restful import Resource
import time
class Test(Resource):
def get(self):
return self.someMethod()
def post(self):
globals.cache.clear()
return self.someMethod()
#globals.cache.cached()
def someMethod(self):
return str(time.ctime())
I have a GET method which needs to the value from the cache and a POST method which updates the cache by first clearing the cache.
However, no matter I call the GET or the POST method, it always gives me the value from the cache.
PS: At the moment I am simply testing on the development server however I do need to deploy it using WSGI later.
I am not sure if it is the best way, but I did it using the following way.
class Test(Resource):
def get(self):
return globals.cache.get('curr_time')
def post(self):
result = self.someMethod()
globals.cache.set('curr_time', result, timeout=3600)
def someMethod(self):
return str(time.ctime())