Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9132479
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T08:19:03+00:00 2026-06-17T08:19:03+00:00

I’m trying to deploy my flask based app on a server, however I have

  • 0

I’m trying to deploy my flask based app on a server, however I have a problem. Basic handlers seems to work fine, however one where I connect to MySQL gives me error 500.

I deploy this app as user flask on Debian linux using apache and mod_wsgi. I logged in as this user and tried to manually run the app on different port, and then it worked perfectly fine.

I checked the flask logs, and this is the error I see:

[Sun Jan 13 14:33:27 2013] [error] [20130113-14:33PM] [susyapi] [ERROR] Exception on /1/product [GET]
[Sun Jan 13 14:33:27 2013] [error] Traceback (most recent call last):
[Sun Jan 13 14:33:27 2013] [error]   File "/usr/local/lib/python2.6/dist-packages/flask/app.py", line 1687, in wsgi_app
[Sun Jan 13 14:33:27 2013] [error]     response = self.full_dispatch_request()
[Sun Jan 13 14:33:27 2013] [error]   File "/usr/local/lib/python2.6/dist-packages/flask/app.py", line 1360, in full_dispatch_request
[Sun Jan 13 14:33:27 2013] [error]     rv = self.handle_user_exception(e)
[Sun Jan 13 14:33:27 2013] [error]   File "/usr/local/lib/python2.6/dist-packages/flask/app.py", line 1358, in full_dispatch_request
[Sun Jan 13 14:33:27 2013] [error]     rv = self.dispatch_request()
[Sun Jan 13 14:33:27 2013] [error]   File "/usr/local/lib/python2.6/dist-packages/flask/app.py", line 1344, in dispatch_request
[Sun Jan 13 14:33:27 2013] [error]     return self.view_functions[rule.endpoint](**req.view_args)
[Sun Jan 13 14:33:27 2013] [error]   File "/home/pisarzp/susyapi/susyapi.py", line 36, in product_search
[Sun Jan 13 14:33:27 2013] [error]     cur = db.cursor()
[Sun Jan 13 14:33:27 2013] [error] NameError: global name 'db' is not defined

The code of the app is following:

from flask import Flask, url_for, session, redirect, escape, request
from subprocess import Popen, PIPE
import socket
import MySQLdb
import urllib
import json
from datetime import datetime
import decimal
import settings
import logging

@app.route('/')
def api_root():
    return '200 OK test'

@app.route('/version')
def version():
    return '200 OK <BR>Version 0.1'

@app.route('/1/product')
def product_search():
    #get the request parameters
    product_code = request.args.get('code')
    product_code = urllib.unquote(product_code)

    #Fetching all product code from database
    cur = db.cursor() #This is where I get error
    query = "SELECT code from %s GROUP BY 1;" % (settings.DB_PRODUCTS_TABLE)
    cur.execute(query)
    rows = cur.fetchall()

    #Not important part which I cut out
    #...
    # End of cut

    #returning JSON with best matching products info
    products_json = []
    for code in best_matching_codes:
        cur = db.cursor()
        query = "SELECT * FROM %s WHERE code LIKE '%s'" % (settings.DB_PRODUCTS_TABLE, code)

        cur.execute(query)
        columns = [desc[0] for desc in cur.description]
        rows = cur.fetchall()
        for row in rows:
            products_json.append(dict((k,v) for k,v in zip(columns,row)))   

    return json.dumps(products_json, default = date_handler)


logging.basicConfig(
    level=logging.DEBUG,
    format='[%(asctime)s] [%(name)s] [%(levelname)s] %(message)s',
    datefmt='%Y%m%d-%H:%M%p',
)
if __name__ == '__main__':
    app.debug = False
    db=MySQLdb.connect(host=settings.DB_HOST, user=settings.DB_USER, passwd=settings.DB_PASSWD, db=settings.DB_NAME)
    app.run()

—– EDITED —-

I added following changes after the feedback:

def connect_db():
    db_conn = MySQLdb.connect(host=settings.DB_HOST,user=settings.DB_USER,passwd=settings.DB_PASSWD,db=settings.DB_NAME)
    return db_conn

@app.before_request
def db_connect():
    g.db = connect_db()
@app.teardown_request
def db_disconnect(exception=None):
    g.db.close()

But I still get error:

File "/Users/pisarzp/Desktop/SusyChoosy/susyAPI/susyapi.py", line 84, in db_disconnect
g.db.close()
NameError: global name 'g' is not defined

Tried Googling, but couldn’t find anything. Any advice?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T08:19:04+00:00Added an answer on June 17, 2026 at 8:19 am

    The code block after if __name__ == '__main__' condition is ignored by mod_wsgi, you need to set up your DB connection elsewhere. A good place is before_request and teardown_request handlers, so your connection is set up and disposed for each request, otherwise you’re going to have troubles, because MySQL will drop long standing connections:

    from flask import g
    
    @app.before_request
    def db_connect():
        g.db_conn = MySQLdb.connect(host=settings.DB_HOST,
                                    user=settings.DB_USER,
                                    passwd=settings.DB_PASSWD,
                                    db=settings.DB_NAME)
    
    @app.teardown_request
    def db_disconnect(exception=None):
        g.db_conn.close()
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a small JavaScript validation script that validates inputs based on Regex. I
I'm trying to convert HTML to plain text. I get many &\#8217; &\#8220; etc.
I have been unable to fix a problem with Java Unicode and encoding. The
I am trying to loop through a bunch of documents I have to put
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have just tried to save a simple *.rtf file with some websites and

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.