0

I have a Flask project where the entry point is application.py and then I have several other modules like, e.g. variant.py, etc.

The project structure is:

>my_app_dir/
   application.py
   views/
       __init__.py
       users.py
       variant.py
       ...

For variant.py, it's a function like:

import ...
from views import *

def variant(variant_id, subset='all', language='en'):
    ...
    if subset == 'all':
        return json.dumps(x)
    return json.dumps([{subset: y[subset]} for y in x])

The point is I want to use variant.py like an API, so I am testing via iPython, something like, but it's returning an error:

from views import variant as v
aa = v.variant('22-38212762-A-G')
...
RuntimeError: Working outside of request context.

This typically means that you attempted to use functionality that needed
an active HTTP request.  Consult the documentation on testing for
information about how to avoid this problem.

I've tried googling but couldn't find any similar case, yet I experimented several things for no avail.

alanwilter
  • 498
  • 1
  • 3
  • 20
  • you want to use `variant.py` like an API ? i'm expecting you are making `http` requests to an endpoint. it 's not that clear. this thread may be useful https://stackoverflow.com/questions/9931738/flask-throwing-working-outside-of-request-context-when-starting-sub-thread – cizario Jun 25 '20 at 10:12
  • The code works fine for the web application. Since `variant.py` is accessing our postgres DB, I may want to reuse this function in local tests or for quick debuggings and within iPython, where I feel comfortable. – alanwilter Jun 25 '20 at 13:09

1 Answers1

0

In the end, I found out a way to get what I was looking for:

from views import application, autocomplete
from views.variant import variant

ctx = application.test_request_context(path='/login',method='POST', data={'user':'demo','password':'demo123'})
ctx.push()

variant('22-38212762-A-G')[:50]

autocomplete.autocomplete('ttll','gene').json

So, essentially, the trick bit is:

ctx = application.test_request_context(path='/login',method='POST', data={'user':'demo','password':'demo123'})
ctx.push()
alanwilter
  • 498
  • 1
  • 3
  • 20