Friday, February 18, 2022

[SOLVED] Appengine: "URLFetch is not available in this environment."

Issue

I've built an App engine API in Python that's fetched by a Node application. The API works as expected for (1) get and post requests in production and (2) get requests in development. It fails on post requests in development and I could use some help figuring out why.

Error messages

In my node environment I see the error:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4444' is therefore not allowed access. The response had HTTP status code 500. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

But I am already using the flask_cors package inside my app so I wonder if this is really a CORS issue.

My activated virtual python environment logs:

File "/myproject/googleAdsApi/env/lib/python2.7/site-packages/urllib3/contrib/appengine.py", line 103, in init "URLFetch is not available in this environment.")

So perhaps I should use an alternative to URLFetch within my virtual environment?

My current implementation

Fetching:

fetch('http://localhost:8080/api/get_accounts', {
    method: "POST",
    mode: "cors", 
    cache: "no-cache", 
    credentials: "same-origin", 
    headers: {
        "Content-Type": "application/json; charset=utf-8",
    },
    redirect: "follow", 
    referrer: "no-referrer", 
    body: JSON.stringify(credentials)
})
.then(response => response.json())
.then(result => console.log(result));

flask_cors:

app = Flask(__name__)
cors = CORS(app, resources={r"/api/*": {"origins": "*"}})

Solution

Always use dev_appserver.py for running your local development environment on GAE apps. GAE has a lot of peculiarities that are hard to reproduce manually on a local virtualenv. Plus you get a lot of useful tools to monitor various services (Taskqueues, Memcache, Storage, etc). dev_appserver.py also automatically loads a lot of GAE native apis for you to be able to use and very often they have their own versions of popular libs that are adapted for a serverless environment (URLFetch is one of them)

Official Docs https://cloud.google.com/appengine/docs/standard/python/tools/using-local-server



Answered By - Marco Yammine
Answer Checked By - David Goodson (WPSolving Volunteer)