I built a web app with a REST API using Flask. I take advantage of Flask's g to save the current user and pull the user's data I want from the datastore (the app is hosted at Google Cloud). However, I would like to implement Google Cloud Endpoints because of some of its advantages but if I call one of the urls in Cloud Endpoints I get the error:
Traceback (most recent call last):
File "/Users/manuelgodoy/Documents/Google/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 239, in Handle
handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
File "/Users/manuelgodoy/Documents/Google/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 298, in _LoadHandler
handler, path, err = LoadObject(self._handler)
File "/Users/manuelgodoy/Documents/Google/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 95, in LoadObject
__import__(cumulative_path)
File "/Users/manuelgodoy/Projects/Eatsy/Eatsy/src/application/apis.py", line 18, in <module>
user = g.user
File "/Users/manuelgodoy/Projects/Eatsy/Eatsy/src/lib/werkzeug/local.py", line 338, in __getattr__
return getattr(self._get_current_object(), name)
File "/Users/manuelgodoy/Projects/Eatsy/Eatsy/src/lib/werkzeug/local.py", line 297, in _get_current_object
return self.__local()
File "/Users/manuelgodoy/Projects/Eatsy/Eatsy/src/lib/flask/globals.py", line 27, in _lookup_app_object
raise RuntimeError('working outside of application context')
RuntimeError: working outside of application context
How can I use flask's context variables like g, login_required, current_user, etc. for Cloud Endpoints?
In my code I store current_user in g.user and I have an endpoint where I get the g.user so I can get the id.
views.py:
from flask.ext.login import login_user, logout_user, current_user, login_required
from flask import session, g, request
import requests
#app.before_request
def before_request():
log.info('Received request: %s' % request.path)
g.user = current_user
#app.route('/recommendations', methods = ['GET'])
def recommendations_retrieve():
# This HTTP call is what I'd like to get rid off
app_url = request.url_root
usr_id = g.user.key().id()
d = {'id': str(usr_id)}
r = requests.get(urljoin(app_url,"/_ah/api/myapp/v1/recommendations"),
params = d)
return (r.text, r.status_code, r.headers.items())
My Cloud Endpoints file looks like this:
from views import g
#endpoints.api(name='myapp', version='v1', description='myapp API',
allowed_client_ids=[WEB_CLIENT_ID, endpoints.API_EXPLORER_CLIENT_ID])
class MyAppApi(remote.Service):
#endpoints.method(IdRequestMessage, RecommendationsResponseMessage,
path='recommendations', http_method='GET',
name='recommendations.recommendations')
def recommendations(self, request):
# I would prefer to use this, but I get the
# "Working outside the app context" error
# when I uncomment it
#user = User.get_by_id(g.user.key().id())
user = User.get_from_message(request)
response = user.get_recommendations()
return response
My Javascript function is as follows:
loadRecommendationsFromServer: function() {
$.ajax({
// This is how I *would* call it, if it worked
//url: this.props.url+"/_ah/api/myapp/v1/recommendations",
//data: JSON.stringify({'id':2}),
url: this.props.url+"/recommendations",
dataType: 'json',
success: function(data) {
this.setState({data: data.recommendations});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
The existing code works - how can I avoid having to make an HTTP request in my view handler and avoid the RuntimeError in the MyAppApi service when I use g.user?
Related
I have a Firestore database like this:(https://i.stack.imgur.com/QSZ8m.png)
My code intends to update the fields "intensity" and "seconds" (under the document "1", under collection "Event") with the value "test" and 123 respectively.
import firebase_admin
from firebase_admin import credentials
from firebase_admin import db
# Initialize Firebase admin
cred = credentials.Certificate('taiwaneew-firebase-adminsdk-odl9d-222bd18a4e.json')
firebase_admin.initialize_app(cred, {
'databaseURL': 'https://taiwaneew.firebaseio.com/'
})
# Define a function to send data to the Firebase database
def send_data(param1, param2):
ref = db.reference(path='/TaiwanEEW/Event/1')
ref.update({
'intensity': param1,
'seconds': param2
})
# Invoke our function to send data to Firebase
send_data("test", 123)
The code, however, causes the following error:
File "/Users/joelin/PycharmProjects/pythonProject/venv/lib/python3.10/site-packages/firebase_admin/db.py", line 929, in request
return super(_Client, self).request(method, url, **kwargs)
File "/Users/joelin/PycharmProjects/pythonProject/venv/lib/python3.10/site-packages/firebase_admin/_http_client.py", line 119, in request
resp.raise_for_status()
File "/Users/joelin/PycharmProjects/pythonProject/venv/lib/python3.10/site-packages/requests/models.py", line 1021, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://taiwaneew.firebaseio.com/TaiwanEEW/Event/1.json?print=silent
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/joelin/PycharmProjects/pythonProject/eewPush.py", line 20, in <module>
send_data("777", 778)
File "/Users/joelin/PycharmProjects/pythonProject/eewPush.py", line 14, in send_data
ref.update({
File "/Users/joelin/PycharmProjects/pythonProject/venv/lib/python3.10/site-packages/firebase_admin/db.py", line 341, in update
self._client.request('patch', self._add_suffix(), json=value, params='print=silent')
File "/Users/joelin/PycharmProjects/pythonProject/venv/lib/python3.10/site-packages/firebase_admin/db.py", line 931, in request
raise _Client.handle_rtdb_error(error)
firebase_admin.exceptions.NotFoundError: 404 Not Found
I have tried to identify the cause of error but the same error persists. I would really like to hear some opinions if you have any experiences on this. Thank you so much!
I have double checked that my credentials json file is correct, under the same directory as the python file, and my database premissions to write and read set to true.
I tried both '/TaiwanEEW/Event/1' and '/taiwaneew/Event/1' for the reference path because I am not sure if it should be the project name or the database name.
I coud not find the error here, so I come with a workaround.
You can use firebase_admin.firestore.
Then, your db object will be instanciated by db = firestore.client(), and have access to all collections and document (see doc).
Complete solution:
import firebase_admin
from firebase_admin import credentials, firestore
cred = credentials.Certificate('taiwaneew-firebase-adminsdk-odl9d-222bd18a4e.json')
# no need for an url here if your credentials already contain the project id.
firebase_admin.initialize_app(cred)
db = firestore.client()
# Define a function to send data to the Firebase database
def send_data(param1, param2):
doc = db.document('Event/1') # or doc = db.collection('Event').document('1')
doc.update({
'intensity': param1,
'seconds': param2
})
# Invoke our function to send data to Firebase
send_data("test", 123)
I am trying to figure out how to send POST request to Flask app from another python script. But I am getting RuntimeError: Working outside of request context.
Here is my Flask app (app.py):
import datetime
import numpy as np
import pandas as pd
from flask import Flask, jsonify, make_response, Response, request, json
def upload_data(file):
df = pd.read_json(file)
df['Res'] = pd.to_datetime(df['Res'], format="%Y-%d-%m %H:%M:%S")
df['SQQ'] = np.nan
return df
server = Flask(__name__)
#server.route('/results', methods=['POST', 'GET'])
def DL_results_get():
with server.test_request_context('/results'):
if request.method == 'POST':
reqData = request.get_json(force=True)
df_DL = upload_data(reqData)
return df_DL.to_json()
else:
return print('GET is not supported')
if __name__ == '__main__':
server.run(debug=True, port=85)
And here is my script for POST request (request.py):
import datetime
import numpy as np
import pandas as pd
from flask import Flask, jsonify, make_response, Response, request, json
headers = {'content-type': 'application/json', 'Accept': 'application/json'}
dfDL = pd.read_csv('data.csv')
dfDLJson = dfDL.to_json()
myAuthResponse = request.post('http://0.0.0.0:85/results', headers=headers, data=dfDLJson)
dataReturned = json.loads(myAuthResponse.text)
print(dataReturned)
The error message:
Traceback (most recent call last):
File "endpoint.test.py", line 12, in <module>
myAuthResponse = request.post('http://0.0.0.0:85/DL-CA-results', headers=headers, data=dfDLJson)
File "C:\Users\iakubal\Anaconda3\envs\general_3_6\lib\site-packages\werkzeug\local.py", line 347, in __getattr__
return getattr(self._get_current_object(), name)
File "C:\Users\iakubal\Anaconda3\envs\general_3_6\lib\site-packages\werkzeug\local.py", line 306, in _get_current_object
return self.__local()
File "C:\Users\iakubal\Anaconda3\envs\general_3_6\lib\site-packages\flask\globals.py", line 38, in _lookup_req_object
raise RuntimeError(_request_ctx_err_msg)
RuntimeError: Working outside of request context.
I've found a similar question here and I tried to add with server.test_request_context('/results') into code for Flask app, but I still have the same error.
Don't use Flask's request in your python script, use the Python package called request as seen in this answer. You can install requests by
pip install requests
and use it like
>>> import requests
>>> myAuthResponse = requests.post('http://127.0.0.1:5000/results', json=dfDLJson, headers=headers)
>>> myAuthResponse.status_code
200
>>> dataReturned = myAuthResponse.json()
Don't use Flask outside flask
Trying to create google login for django using googleapiclient and oauth2client.
I am able to open home page, and getting redirected to google login successfully. Once after sign-in, it is redirecting to home page where I'm receiving this error.
Reference link/tutorial
views.py
import httplib2
from googleapiclient.discovery import build
from django.http import HttpResponseBadRequest
from django.http import HttpResponseRedirect
from .models import CredentialsModel
from gfglogin import settings
from oauth2client.contrib import xsrfutil
from oauth2client.client import flow_from_clientsecrets
from oauth2client.contrib.django_util.storage import DjangoORMStorage
from django.shortcuts import render
from httplib2 import Http
def home(request):
print("*****home*****")
status = True
if not request.user.is_authenticated:
return HttpResponseRedirect('admin')
storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential')
credential = storage.get()
print(f"credential: {credential}")
print(f"storage: {storage}")
try:
access_token = credential.access_token
resp, cont = Http().request("https://www.googleapis.com/auth/gmail.readonly",
headers={'Host': 'www.googleapis.com',
'Authorization': access_token})
except:
status = False
print('Not Found')
return render(request, 'index.html', {'status': status})
################################
# GMAIL API IMPLEMENTATION #
################################
# CLIENT_SECRETS, name of a file containing the OAuth 2.0 information for this
# application, including client_id and client_secret, which are found
# on the API Access tab on the Google APIs
# Console <http://code.google.com/apis/console>
FLOW = flow_from_clientsecrets(
settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON,
scope='https://www.googleapis.com/auth/gmail.readonly',
redirect_uri='http://127.0.0.1:8080/oauth2callback',
prompt='consent')
def gmail_authenticate(request):
print("*****gmail_authenticate*****")
storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential')
credential = storage.get()
print(f"credential: {credential}")
if credential is None or credential.invalid:
FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY,
request.user)
authorize_url = FLOW.step1_get_authorize_url()
return HttpResponseRedirect(authorize_url)
else:
http = httplib2.Http()
http = credential.authorize(http)
service = build('gmail', 'v1', http=http)
print('access_token = ', credential.access_token)
status = True
return render(request, 'index.html', {'status': status})
def auth_return(request):
print("*****auth_return*****")
get_state = bytes(request.GET.get('state'), 'utf8')
if not xsrfutil.validate_token(settings.SECRET_KEY, get_state,
request.user):
return HttpResponseBadRequest()
credential = FLOW.step2_exchange(request.GET.get('code'))
print(f"credential: {credential}")
storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential')
storage.put(credential)
print(f"storage: {storage}")
print("access_token: %s" % credential.access_token)
return HttpResponseRedirect("/")
Error:
System check identified no issues (0 silenced).
June 06, 2020 - 14:38:49
Django version 3.0.7, using settings 'gfglogin.settings'
Starting development server at http://127.0.0.1:8080/
Quit the server with CTRL-BREAK.
[06/Jun/2020 14:39:00] "GET /admin/ HTTP/1.1" 200 3042
*****home*****
credential: None
storage: <oauth2client.contrib.django_util.storage.DjangoORMStorage object at 0x0000014A630EABE0>
Not Found
[06/Jun/2020 14:39:05] "GET / HTTP/1.1" 200 327
*****gmail_authenticate*****
credential: None
[06/Jun/2020 14:39:07] "GET /gmailAuthenticate HTTP/1.1" 302 0
*****auth_return*****
credential: <oauth2client.client.OAuth2Credentials object at 0x0000014A6322BA00>
storage: <oauth2client.contrib.django_util.storage.DjangoORMStorage object at 0x0000014A6322B550>
access_token: ya29.a0AfH6SMBLyCWC3cV4iiMk0jWUJaw8ruUFoBqFTkM5LT2acAc6FelcoADU3tn67RslO-24dKEFqrdp4tcLFVuEIMvmn7cHKeb8XeZ9YNQozRoRSTU6hs-jMA9bHP10epw1ImbBaY8SUgQUtF75mRRniR0aELEmzTVKGe8
[06/Jun/2020 14:40:26] "GET /oauth2callback?state=VaASAVe2IusAHCsQfc7EfToxNTkxNDM0NTQ3&code=4/0gFCWPMx4qTUrv4wUWpSKbA8Z_rTaZb-YGGDRrK4NsK2UiW6f4MpA_g1Pr5RpyGcRxbCtWlH6qHvKIJvbpG_L9c&scope=https://www.googleapis.com/auth/gmail.readonly HTTP/1.1" 302 0
*****home*****
Internal Server Error: /
Traceback (most recent call last):
File "D:\PERSONAL DATA\env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "D:\PERSONAL DATA\env\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "D:\PERSONAL DATA\env\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\PERSONAL DATA\raw_login\google-oauth-mail\gfgauth\views.py", line 23, in home
credential = storage.get()
File "D:\PERSONAL DATA\env\lib\site-packages\oauth2client\client.py", line 407, in get
return self.locked_get()
File "D:\PERSONAL DATA\env\lib\site-packages\oauth2client\contrib\django_util\storage.py", line 58, in locked_get
if len(entities) > 0:
File "D:\PERSONAL DATA\env\lib\site-packages\django\db\models\query.py", line 258, in __len__
self._fetch_all()
File "D:\PERSONAL DATA\env\lib\site-packages\django\db\models\query.py", line 1261, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "D:\PERSONAL DATA\env\lib\site-packages\django\db\models\query.py", line 74, in __iter__
for row in compiler.results_iter(results):
File "D:\PERSONAL DATA\env\lib\site-packages\django\db\models\sql\compiler.py", line 1096, in apply_converters
value = converter(value, expression, connection)
TypeError: from_db_value() missing 1 required positional argument: 'context'
One of SO post, suggest to replace context argument with *args, **kwargs. I'm not able to see from_db_value method in source code.
versions:
django == 3.0.7
python == 3.8
Can anyone please respond to this question and help?
I have also seen that oauth2client is depreciated. Is there any other library with clear example that I can follow? or Can anyone post example code?
In github issue, someone says
You can't use oauth2client's storage with google-auth. google-auth
credentials are relatively straight forward to persist, see:
https://github.com/GoogleCloudPlatform/google-auth-library-python-oauthlib/blob/master/google_auth_oauthlib/tool/main.py#L80
But, as new to this, I'm not able to understand implement this. Please help!
The problem seems to be with oauth2client, which is no longer updated or supported. From the README:
Note: oauth2client is now deprecated. No more features will be added to the libraries and the core team is turning down support. We recommend you use google-auth and oauthlib. For more details on the deprecation, see oauth2client deprecation.
So I'd suggest you take a look at those two packages and integrate those instead.
The takeaway here is that you should be more careful about the tutorials you choose. This one uses Django 2.0, which hasn't been supported for over a year. Always look for tutorials which match either the latest release or the latest LTS release, or you're asking for trouble.
I'm writing an endpoint to receive and parse GitHub Webhook payloads using Django Rest Framework 3. In order to match the payload specification, I'm writing a payload request factory and testing that it's generating valid requests.
However, the problem comes when trying to test the request generated with DRF's Request class. Here's the smallest failing test I could come up with - the problem is that a request generated with DRF's APIRequestFactory seems to not be parsable by DRF's Request class. Is that expected behaviour?
from rest_framework.request import Request
from rest_framework.parsers import JSONParser
from rest_framework.test import APIRequestFactory, APITestCase
class TestRoundtrip(APITestCase):
def test_round_trip(self):
"""
A DRF Request can be loaded into a DRF Request object
"""
request_factory = APIRequestFactory()
request = request_factory.post(
'/',
data={'hello': 'world'},
format='json',
)
result = Request(request, parsers=(JSONParser,))
self.assertEqual(result.data['hello'], 'world')
And the stack trace is:
E
======================================================================
ERROR: A DRF Request can be loaded into a DRF Request object
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/james/active/prlint/venv/lib/python3.4/site-packages/rest_framework/request.py", line 380, in __getattribute__
return getattr(self._request, attr)
AttributeError: 'WSGIRequest' object has no attribute 'data'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/james/active/prlint/prlint/github/tests/test_payload_factories/test_roundtrip.py", line 22, in test_round_trip
self.assertEqual(result.data['hello'], 'world')
File "/home/james/active/prlint/venv/lib/python3.4/site-packages/rest_framework/request.py", line 382, in __getattribute__
six.reraise(info[0], info[1], info[2].tb_next)
File "/home/james/active/prlint/venv/lib/python3.4/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/home/james/active/prlint/venv/lib/python3.4/site-packages/rest_framework/request.py", line 186, in data
self._load_data_and_files()
File "/home/james/active/prlint/venv/lib/python3.4/site-packages/rest_framework/request.py", line 246, in _load_data_and_files
self._data, self._files = self._parse()
File "/home/james/active/prlint/venv/lib/python3.4/site-packages/rest_framework/request.py", line 312, in _parse
parsed = parser.parse(stream, media_type, self.parser_context)
File "/home/james/active/prlint/venv/lib/python3.4/site-packages/rest_framework/parsers.py", line 64, in parse
data = stream.read().decode(encoding)
AttributeError: 'str' object has no attribute 'read'
----------------------------------------------------------------------
I'm obviously doing something stupid - I've messed around with encodings... realised that I needed to pass the parsers list to the Request to avoid the UnsupportedMediaType error, and now I'm stuck here.
Should I do something different? Maybe avoid using APIRequestFactory? Or test my built GitHub requests a different way?
More info
GitHub sends a request out to registered webhooks that has a X-GitHub-Event header and therefore in order to test my webhook DRF code I need to be able to emulate this header at test time.
My path to succeeding with this has been to build a custom Request and load a payload using a factory into it. This is my factory code:
def PayloadRequestFactory():
"""
Build a Request, configure it to look like a webhook payload from GitHub.
"""
request_factory = APIRequestFactory()
request = request_factory.post(url, data=PingPayloadFactory())
request.META['HTTP_X_GITHUB_EVENT'] = 'ping'
return request
The issue has arisen because I want to assert that PayloadRequestFactory is generating valid requests for various passed arguments - so I'm trying to parse them and assert their validity but DRF's Request class doesn't seem to be able to achieve this - hence my question with a failing test.
So really my question is - how should I test this PayloadRequestFactory is generating the kind of request that I need?
"Yo dawg, I heard you like Request, cos' you put a Request inside a Request" XD
I'd do it like this:
from rest_framework.test import APIClient
client = APIClient()
response = client.post('/', {'github': 'payload'}, format='json')
self.assertEqual(response.data, {'github': 'payload'})
# ...or assert something was called, etc.
Hope this helps
Looking at the tests for APIRequestFactory in
DRF, stub
views
are created and then run through that view - the output is inspected for expected results.
Therefore a reasonable, but slightly long solution, is to copy this strategy to
assert that the PayloadRequestFactory is building valid requests, before then
pointing that at a full view.
The test above becomes:
from django.conf.urls import url
from django.test import TestCase, override_settings
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.test import APIRequestFactory
#api_view(['POST'])
def view(request):
"""
Testing stub view to return Request's data and GitHub event header.
"""
return Response({
'header_github_event': request.META.get('HTTP_X_GITHUB_EVENT', ''),
'request_data': request.data,
})
urlpatterns = [
url(r'^view/$', view),
]
#override_settings(ROOT_URLCONF='github.tests.test_payload_factories.test_roundtrip')
class TestRoundtrip(TestCase):
def test_round_trip(self):
"""
A DRF Request can be loaded via stub view
"""
request_factory = APIRequestFactory()
request = request_factory.post(
'/view/',
data={'hello': 'world'},
format='json',
)
result = view(request)
self.assertEqual(result.data['request_data'], {'hello': 'world'})
self.assertEqual(result.data['header_github_event'], '')
Which passes :D
I have the following python script:
from flask import Flask, render_template, json, request
from flask import Flask, request, abort, jsonify
from flaskext.mysql import MySQL
import MySQLdb
app = Flask(__name__)
#app.route("/")
def main():
return render_template('testFirst.html')
#app.route("/form_submit/", methods=['POST'])
print ("outside function")
def connect():
import json
dtb = request.select['value'] #i want the selected drop down value to be set here which will be used to connect to the database
db = MySQLdb.connect("localhost","root","",dtb)
cursor = db.cursor()
cursor.execute("SELECT * FROM REPORT_SUITE")
results = cursor.fetchall()
json_return_value =[]
for result in results:
table_data = {'REPORTSUITE_ID' : result[0], 'REPORTSUITE_NAME' : result[1], 'STAGING_DATABASE' : result[2], 'DWH_DATABASE' : result[3], 'TRANS_TABLE' : result[4]}
json_return_value.append(table_data)
print ("hi")
print json.dumps(json_return_value)
return json.dumps(json_return_value)
connect()
if __name__ == "__main__":
app.run(debug = True)
It renders the following html file:
$(document).ready(function(){
$("button").click(function(){
$.ajax({
url : "/form_submit/",
data : $('#databases').val(),
type : 'POST',
success : alert("Hi dear count ")
});
});
});
<body>
<select id ="databases">
<option value = "">--Select From following--</option>
<option value = "OMTSL_QBO">OMTSL_QBO</option>
<option value = "OMTSL_SBG">OMTSL_SBG</option>
<option value = "OMTSL_PTX">OMTSL_PTX</option>
</select>
<br><br>
<button type = "button"> Click Me!!</button>
<div id ="placeholder"></div>
</body>
</html>
The HTML form should call the python script through an ajax call by passing the selected value from the drop down to the connect() method.
when i run main.py, i get the following error
Traceback (most recent call last):
File "main.py", line 31, in <module>
connect()
File "main.py", line 16, in connect
dtb = request.select['value']
File "/Library/Python/2.7/site-packages/werkzeug/local.py", line 338, in __getattr__
return getattr(self._get_current_object(), name)
File "/Library/Python/2.7/site-packages/werkzeug/local.py", line 297, in _get_current_object
return self.__local()
File "/Library/Python/2.7/site-packages/flask/globals.py", line 20, in _lookup_req_object
raise RuntimeError('working outside of request context')
RuntimeError: working outside of request context
I do not know how to pass the drop down value to the called python fucntion. I tried to look for it but i have still not found the way to
do it. Please help me through this
Ajax uses HTTP, so you cant call a python script directly (unless you have specifically built your setup to work that way).
Your ajax should look something like:
$(document).ready(function(){ $("button").click(function(){ $.ajax({ url : "/form_submit/", data : $('#databases').val(), type : 'POST', //success : alert("Hi "+ $('#databases').val()) success : alert("Hi dear count ") }); }); });
Then have a Flask function decorated with #app.router('/form_submit/') under which you would then handle the form data as per the Flask tutorial.
You shouldn't have a separate "Python script". It should be another handler in your Flask app, with a route, which your Ajax script calls.
In your second code, you're sending the call from ajax using POST, while in your Flask code you have
#app.route("/form_submit/", methods=['GET'])
Change this line into:
#app.route("/form_submit/", methods=['GET', 'POST'])