In-memory data in a Flask app - flask

I think the correct way to have instance variables in Flask is by adding users and sessions, but I'm trying to test a concept and I don't want to go through all of that just yet. I'm trying to have a web app load an image into a variable that can then have different image operations performed on it. Obviously you don't want to have to keep performing a list of operations on the image on each new request because that would be horribly inefficient.
Is there a way of having an app.var in Flask that I can access from different routes? I've tried using the global context and Flask's current_app, but I get the impression that's not what they're for.
The code for my blueprint is:
import os
from flask import Flask, url_for, render_template, \
g, send_file, Blueprint
from io import BytesIO
from PIL import Image, ImageDraw, ImageOps
home = Blueprint('home', __name__)
#home.before_request
def before_request():
g.img = None
g.user = None
#home.route('/')
def index():
return render_template('home/index.html')
#home.route('/image')
def image():
if g.img is None:
root = os.path.dirname(os.path.abspath(__file__))
filename = os.path.join(root, '../static/images/lena.jpg')
g.img = Image.open(filename)
img_bytes = BytesIO()
g.img.save(img_bytes, 'jpeg')
img_bytes.seek(0)
return send_file(img_bytes, mimetype='image/jpg')
#home.route('/grayscale', methods=['POST'])
def grayscale():
if g.img:
print('POST grayscale request')
g.img = ImageOps.grayscale(img)
return "Grayscale operation successful"
else:
print('Grayscale called with no image loaded')
return "Grayscale operation failed"
The /image route returns the image correctly, but I'd like to be able to call /grayscale, perform the operation, and be able to make another call to /image and have it return the image from memory without loading it.

You could save a key in your session variable and use that to identify the image in a global dictionary. However this might lead to some trouble if you use multiple Flask application instances. But with one it would be fine. Otherwise you could use Redis when working with multiple workers. I haven't tried the following code but it should show the concept.
from flask import session
import uuid
app.config['SECRET_KEY'] = 'your secret key'
img_dict = {}
#route('/image')
def image():
key = session.get('key')
if key is None:
session['key'] = key = uuid.uuid1()
img_dict[key] = yourimagedata
#home.route('/grayscale', methods=['POST'])
def grayscale():
key = session.get('key')
if key is None:
print('Grayscale called with no image loaded')
return "Grayscale operation failed"
else:
img = img_dict[key]
print('POST grayscale request')
g.img = ImageOps.grayscale(img)
return "Grayscale operation successful"

Related

Flask Form Image to base64 string

I created a Flask form where I can upload an image. Then I need to convert that image to base64 string, but I'm always getting the same result.
OUTPUT of my prints:
<FileStorage: '20190925_184412.jpg' ('image/jpeg')>
b''
And the code
from flask import Flask, render_template
from flask_wtf import FlaskForm
from wtforms import FileField
from flask_uploads import configure_uploads, IMAGES, UploadSet
import base64
app = Flask(__name__)
app.config['SECRET_KEY'] = 'thisisasecret'
app.config['UPLOADED_IMAGES_DEST'] = 'uploads/images'
images = UploadSet('images', IMAGES)
configure_uploads(app, images)
class MyForm(FlaskForm):
image = FileField('image')
#app.route('/', methods=['GET', 'POST'])
def index():
form = MyForm()
if form.validate_on_submit():
filename = images.save(form.image.data)
image_string = base64.b64encode(form.image.data.read())
print(form.image.data)
print(image_string)
return f'Filename: { filename }'
return render_template('index.html', form=form)
I think this is due to the way Werkzeug's FileStorage object works. As I menioned in another answer it has a stream attribute; this is of type tempfile.SpooledTemporaryFile so must be re-wound after reading, if you wish to read it again.
In your case this stream attribute is: form.image.data.stream. I suspect this is read once when you call the method images.save.
So the solution should be to rewind that stream, prior to calculating the the b64 string:
if form.validate_on_submit():
filename = images.save(form.image.data) # first read happens here
form.image.data.stream.seek(0)
image_string = base64.b64encode(form.image.data.read())
print(form.image.data)
print(image_string)
return f'Filename: { filename }'

set time to live for each session separately KVsession flask

KBsession stores the session TTL based on PERMANENT_SESSION_LIFETIME is there a way to override this for specific sessions
EDIT:
so I have two different API for login I need to give any user login from one of them an infinite session TTL, the other one will take PERMANENT_SESSION_LIFETIME value
note: KBsession back-end is redis
I think the best way is use Session Interface to create specific processing. This is just an example, but I hope you can understand approach.
from flask import Flask, session as flask_session, jsonify
flask_app = Flask(__name__)
# just a few user types
UNIQUE_USER_TYPE = 'unique'
DEFAULT_USER_TYPE = 'default'
#flask_app.route('/login-default')
def login_default():
flask_session['user_type'] = DEFAULT_USER_TYPE
return 'login default done'
#flask_app.route('/login-unique')
def login_unique():
flask_session['user_type'] = UNIQUE_USER_TYPE
return 'login unique done'
#flask_app.route('/session-state')
def get_session_state():
return jsonify(dict(flask_session))
class UserTypeSessionInterface(SecureCookieSessionInterface):
def get_expiration_time(self, app, session):
"""
I just override method. Just demonstration.
It's called from save_session() and open_session()
"""
if session.get('user_type') == UNIQUE_USER_TYPE:
# set 1 hour for unique users
delta = datetime.utcnow() + timedelta(hours=1)
else:
# set 3 hour for default users
delta = datetime.utcnow() + timedelta(hours=3)
# add datetime data into session
session['lifetime'] = delta.strftime('%Y-%m-%dT%H:%M:%S')
return delta
# use our custom session implementation
flask_app.session_interface = UserTypeSessionInterface()
Now run server, open new private window, /login-default and /session-state:
# default behaviour
{
"lifetime": "2018-11-06T16:22:21",
"user_type": "default"
}
Open one more private window, /login-unique and /session-state:
# unique behaviour
{
"lifetime": "2018-11-06T14:25:17",
"user_type": "unique"
}
So, session store tool doesn't matter(redis, cassandra or something else). All what you need is just implement open_session() and save_session():
class YourSessionProcessor(SessionInterface):
def open_session(self, app, request):
# just do here all what you need
pass
def save_session(self, app, session, response):
# just do here all what you need
pass
flask_app.session_interface = YourSessionProcessor()
Also you can use custom session class(just an example):
from flask.sessions import SessionMixin
from werkzeug.datastructures import CallbackDict
class CustomSession(CallbackDict, SessionMixin):
def __init__(self, initial=None, sid=None):
def on_update(self):
self.modified = True
CallbackDict.__init__(self, initial, on_update=on_update)
self.sid = sid
self.modified = False
# YourSessionProcessor
def open_session(self, app, request):
# you can find any useful data in request
# you can find all settings in app.config
sid = request.cookies.get(app.session_cookie_name)
# ... do here everything what you need
return CustomSession(sid=sid)
Hope this helps.

Using Memcached with Flask Blueprints

Within the application context, I can't seem to set objects in memcached. Logs indicate that I connect to memcached, but when I attempt to set an object the set function returns "0" or False. Outside of the application context, I can connect to the server IP and port, and easily get and set objects. Here is my setup:
application/__init__.py
class App(Flask):
def __init__(self):
super(App, self).__init__(__name__)
self.config.from_object('app.config')
self.config.from_object('app.deployments.Prod')
logging.basicConfig(filename=self.config['LOG_PATH'] + config.LOG_FILE, level=logging.INFO, format=config.LOG_FORMAT, datefmt='%m/%d/%Y %I:%M:%S')
self.static_folder=config.STATICS
self.before_request(self.init_dbs)
self.teardown_request(self.teardown)
self.after_request(self.teardown)
try:
self.init_session()
self.init_login()
self.init_templates()
except Exception as e:
logging.info(e)
def init_dbs(self):
g.ES = init_elasticsearch(hosts=self.config['ES_HOSTS'])
g.MEMCACHED = init_memcached(host=self.config['MEMCACHED_HOST'],port=self.config['MEMCACHED_PORT'])
...
cache/__init__.py
from werkzeug.contrib.cache import MemcachedCache
import gevent
import logging
def init_memcached(host,port):
memcached_connected = False
while not memcached_connected:
try:
MEMCACHED = MemcachedCache([host + ':' + str(port)])
memcached_connected = True
except Exception as e:
logging.info("Memcached not connected")
logging.error(e)
gevent.sleep(1)
return MEMCACHED
controllers/page.py
from flask import Blueprint, request, render_template, url_for, flash, g, redirect
from flask.views import MethodView
from flask.ext.login import current_user
from json import dumps
from app import config
...
items = Blueprint(
'items',
__name__,
template_folder=config.TEMPLATES,
)
class Item(MethodView):
def get(self,item):
result = g.MEMCACHED.get('item')
if result is None:
...
g.MEMCACHED.set('item', result, timeout=60)
return render_template('item.html',result=result)
items.add_url_rule("/path/<item>", view_func=Item.as_view('item'))
I'm assuming this has something to do with using memcached within the g object. I'd prefer setting the connection to memcached once, as I'm doing with the dbs, but it seems like memcached doesn't respond in the same way.

Beaker session in bottle

while using beaker session, i came across to use same session object along the whole application.
I came through this url: Bottle.py session with Beaker
But, still i am getting 'KeyError' when i am trying to access the save session value in one function by another function.
my rest.py file looks like:
import bottle
from bottle import route,default_app
from beaker.middleware import SessionMiddleware
app = bottle.default_app()
#bottle.hook('before_request')
def setup_request():
request.session = request.environ['beaker.session']
#app.route('/login')
def login():
request.session['uname'] = 'user'
#app.route('/logout')
def logout():
print request.session['uname']
# expecting to print user
session_opts = {
'session.type': 'file',
'session.data_dir': '/tmp/',
'session.cookie_expires': True,
}
app = SessionMiddleware(bottle.default_app(),session_opts)
I have mentioned the SessionMiddleware at the end as im getting errors with the help of this link https://groups.google.com/forum/#!topic/bottlepy/m0akSbWRpZg
But when i am accessing request.session in the logout function i am getting
'KeyError': Uname not found
can any one give clear example of how to adjust the code inorder to maintain same session in whole application.

how to unit test file upload in django

In my django app, I have a view which accomplishes file upload.The core snippet is like this
...
if (request.method == 'POST'):
if request.FILES.has_key('file'):
file = request.FILES['file']
with open(settings.destfolder+'/%s' % file.name, 'wb+') as dest:
for chunk in file.chunks():
dest.write(chunk)
I would like to unit test the view.I am planning to test the happy path as well as the fail path..ie,the case where the request.FILES has no key 'file' , case where request.FILES['file'] has None..
How do I set up the post data for the happy path?Can somebody tell me?
I used to do the same with open('some_file.txt') as fp: but then I needed images, videos and other real files in the repo and also I was testing a part of a Django core component that is well tested, so currently this is what I have been doing:
from django.core.files.uploadedfile import SimpleUploadedFile
def test_upload_video(self):
video = SimpleUploadedFile("file.mp4", "file_content", content_type="video/mp4")
self.client.post(reverse('app:some_view'), {'video': video})
# some important assertions ...
In Python 3.5+ you need to use bytes object instead of str. Change "file_content" to b"file_content"
It's been working fine, SimpleUploadedFile creates an InMemoryFile that behaves like a regular upload and you can pick the name, content and content type.
From Django docs on Client.post:
Submitting files is a special case. To POST a file, you need only
provide the file field name as a key, and a file handle to the file
you wish to upload as a value. For example:
c = Client()
with open('wishlist.doc') as fp:
c.post('/customers/wishes/', {'name': 'fred', 'attachment': fp})
I recommend you to take a look at Django RequestFactory. It's the best way to mock data provided in the request.
Said that, I found several flaws in your code.
"unit" testing means to test just one "unit" of functionality. So,
if you want to test that view you'd be testing the view, and the file
system, ergo, not really unit test. To make this point more clear. If
you run that test, and the view works fine, but you don't have
permissions to save that file, your test would fail because of that.
Other important thing is test speed. If you're doing something like
TDD the speed of execution of your tests is really important.
Accessing any I/O is not a good idea.
So, I recommend you to refactor your view to use a function like:
def upload_file_to_location(request, location=None): # Can use the default configured
And do some mocking on that. You can use Python Mock.
PS: You could also use Django Test Client But that would mean that you're adding another thing more to test, because that client make use of Sessions, middlewares, etc. Nothing similar to Unit Testing.
I do something like this for my own event related application but you should have more than enough code to get on with your own use case
import tempfile, csv, os
class UploadPaperTest(TestCase):
def generate_file(self):
try:
myfile = open('test.csv', 'wb')
wr = csv.writer(myfile)
wr.writerow(('Paper ID','Paper Title', 'Authors'))
wr.writerow(('1','Title1', 'Author1'))
wr.writerow(('2','Title2', 'Author2'))
wr.writerow(('3','Title3', 'Author3'))
finally:
myfile.close()
return myfile
def setUp(self):
self.user = create_fuser()
self.profile = ProfileFactory(user=self.user)
self.event = EventFactory()
self.client = Client()
self.module = ModuleFactory()
self.event_module = EventModule.objects.get_or_create(event=self.event,
module=self.module)[0]
add_to_admin(self.event, self.user)
def test_paper_upload(self):
response = self.client.login(username=self.user.email, password='foz')
self.assertTrue(response)
myfile = self.generate_file()
file_path = myfile.name
f = open(file_path, "r")
url = reverse('registration_upload_papers', args=[self.event.slug])
# post wrong data type
post_data = {'uploaded_file': i}
response = self.client.post(url, post_data)
self.assertContains(response, 'File type is not supported.')
post_data['uploaded_file'] = f
response = self.client.post(url, post_data)
import_file = SubmissionImportFile.objects.all()[0]
self.assertEqual(SubmissionImportFile.objects.all().count(), 1)
#self.assertEqual(import_file.uploaded_file.name, 'files/registration/{0}'.format(file_path))
os.remove(myfile.name)
file_path = import_file.uploaded_file.path
os.remove(file_path)
I did something like that :
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase
from django.core.urlresolvers import reverse
from django.core.files import File
from django.utils.six import BytesIO
from .forms import UploadImageForm
from PIL import Image
from io import StringIO
def create_image(storage, filename, size=(100, 100), image_mode='RGB', image_format='PNG'):
"""
Generate a test image, returning the filename that it was saved as.
If ``storage`` is ``None``, the BytesIO containing the image data
will be passed instead.
"""
data = BytesIO()
Image.new(image_mode, size).save(data, image_format)
data.seek(0)
if not storage:
return data
image_file = ContentFile(data.read())
return storage.save(filename, image_file)
class UploadImageTests(TestCase):
def setUp(self):
super(UploadImageTests, self).setUp()
def test_valid_form(self):
'''
valid post data should redirect
The expected behavior is to show the image
'''
url = reverse('image')
avatar = create_image(None, 'avatar.png')
avatar_file = SimpleUploadedFile('front.png', avatar.getvalue())
data = {'image': avatar_file}
response = self.client.post(url, data, follow=True)
image_src = response.context.get('image_src')
self.assertEquals(response.status_code, 200)
self.assertTrue(image_src)
self.assertTemplateUsed('content_upload/result_image.html')
create_image function will create image so you don't need to give static path of image.
Note : You can update code as per you code.
This code for Python 3.6.
from rest_framework.test import force_authenticate
from rest_framework.test import APIRequestFactory
factory = APIRequestFactory()
user = User.objects.get(username='#####')
view = <your_view_name>.as_view()
with open('<file_name>.pdf', 'rb') as fp:
request=factory.post('<url_path>',{'file_name':fp})
force_authenticate(request, user)
response = view(request)
As mentioned in Django's official documentation:
Submitting files is a special case. To POST a file, you need only provide the file field name as a key, and a file handle to the file you wish to upload as a value. For example:
c = Client()
with open('wishlist.doc') as fp:
c.post('/customers/wishes/', {'name': 'fred', 'attachment': fp})
More Information: How to check if the file is passed as an argument to some function?
While testing, sometimes we want to make sure that the file is passed as an argument to some function.
e.g.
...
class AnyView(CreateView):
...
def post(self, request, *args, **kwargs):
attachment = request.FILES['attachment']
# pass the file as an argument
my_function(attachment)
...
In tests, use Python's mock something like this:
# Mock 'my_function' and then check the following:
response = do_a_post_request()
self.assertEqual(mock_my_function.call_count, 1)
self.assertEqual(
mock_my_function.call_args,
call(response.wsgi_request.FILES['attachment']),
)
if you want to add other data with file upload then follow the below method
file = open('path/to/file.txt', 'r', encoding='utf-8')
data = {
'file_name_to_receive_on_backend': file,
'param1': 1,
'param2': 2,
.
.
}
response = self.client.post("/url/to/view", data, format='multipart')`
The only file_name_to_receive_on_backend will be received as a file other params received normally as post paramas.
In Django 1.7 there's an issue with the TestCase wich can be resolved by using open(filepath, 'rb') but when using the test client we have no control over it. I think it's probably best to ensure file.read() returns always bytes.
source: https://code.djangoproject.com/ticket/23912, by KevinEtienne
Without rb option, a TypeError is raised:
TypeError: sequence item 4: expected bytes, bytearray, or an object with the buffer interface, str found
from django.test import Client
from requests import Response
client = Client()
with open(template_path, 'rb') as f:
file = SimpleUploadedFile('Name of the django file', f.read())
response: Response = client.post(url, format='multipart', data={'file': file})
Hope this helps.
Very handy solution with mock
from django.test import TestCase, override_settings
#use your own client request factory
from my_framework.test import APIClient
from django.core.files import File
import tempfile
from pathlib import Path
import mock
image_mock = mock.MagicMock(spec=File)
image_mock.name = 'image.png' # or smt else
class MyTest(TestCase):
# I assume we want to put this file in storage
# so to avoid putting garbage in our MEDIA_ROOT
# we're using temporary storage for test purposes
#override_settings(MEDIA_ROOT=Path(tempfile.gettempdir()))
def test_send_file(self):
client = APIClient()
client.post(
'/endpoint/'
{'file':image_mock},
format="multipart"
)
I am using Python==3.8.2 , Django==3.0.4, djangorestframework==3.11.0
I tried self.client.post but got a Resolver404 exception.
Following worked for me:
import requests
upload_url='www.some.com/oaisjdoasjd' # your url to upload
with open('/home/xyz/video1.webm', 'rb') as video_file:
# if it was a text file we would perhaps do
# file = video_file.read()
response_upload = requests.put(
upload_url,
data=video_file,
headers={'content-type': 'video/webm'}
)
I am using django rest framework and I had to test the upload of multiple files.
I finally get it by using format="multipart" in my APIClient.post request.
from rest_framework.test import APIClient
...
self.client = APIClient()
with open('./photo.jpg', 'rb') as fp:
resp = self.client.post('/upload/',
{'images': [fp]},
format="multipart")
I am using GraphQL, upload for test:
with open('test.jpg', 'rb') as fp:
response = self.client.execute(query, variables, data={'image': [fp]})
code in class mutation
#classmethod
def mutate(cls, root, info, **kwargs):
if image := info.context.FILES.get("image", None):
kwargs["image"] = image
TestingMainModel.objects.get_or_create(
id=kwargs["id"],
defaults=kwargs
)