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 8739327
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T10:54:55+00:00 2026-06-13T10:54:55+00:00

I’m trying to pull the value of a variable from inside a function in

  • 0

I’m trying to pull the value of a variable from inside a function in Python, but I’m having a bit of trouble.

uri = None
clientHostname = None
clientIP = None
...
# Handles requests
class DataHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    def do_HEAD(dServe):
        dServe.send_response(200)
        dServe.send_header("connection-type", "text/html")
        dServe.end_headers()
    def do_GET(dServe):
        global uri
        dServe.send_response(200)
        dServe.send_header("connection-type", "text/html")
        uri = dServe.path
        dServe.end_headers()
        clientHostname = dServe.address_string()
        clientIP = dServe.connection.getsockname()[0]
    print(uri)
    print(clientHostname)
    print(clientIP)

When I try and execute this, they only return the value ‘None’. Any pointers? This is my first endeavor into Python(2.7) and I’m still climbing the bell curve on it.

My fulls script is currently:

import time
import BaseHTTPServer
import StringIO
import csv
import sqlite3 as sql
import SimpleHTTPServer
import SocketServer
import multiprocessing
import os


# Initial Variables
appsTable = "Apps"
groupsTable = "Groups"
hostName = 'localhost'
dataPort = 277
filePort = 438
dbFile = "Get-App.db"
uri = None
    clientHostname = None
    clientIP = None
if os.name == "nt":
    dbPath = "Dependencies\sqlite3"
else:
    dbPath = "Dependencies/sqlite3"

# Checks for DB and creates if not found
if os.path.exists(dbFile):
    print("Database found!")
else:
    print("Creating New Database...")
    os.system("echo .tables | " + dbPath + " " + dbFile)
    sqlConnect = None
    try:
        sqlConnect = sql.connect(dbFile)
        sqlCursor = sqlConnect.cursor()
        sqlCursor.execute('CREATE TABLE ' + appsTable + '(ID INTEGER PRIMARY KEY ASC, Name TEXT, InstallGroup TEXT, Version TEXT, Arch TEXT, Executable TEXT, Path TEXT, Command TEXT, Latest BOOL, Enabled BOOL)')
        sqlCursor.execute('CREATE TABLE ' + groupsTable + '(ID INTEGER PRIMARY KEY ASC, Name TEXT, AppList TEXT, Version TEXT, Arch TEXT, Latest BOOL, Enabled BOOL)')
    finally:
        if sqlConnect:
            sqlConnect.close

# Serves files
def file_serve():
    if not os.path.exists(dbFile):
        os.makedirs(appsTable)
    os.chdir(appsTable)
    FileHandler = SimpleHTTPServer.SimpleHTTPRequestHandler
    fileServer = SocketServer.TCPServer(("", filePort), FileHandler)
    fileServer.serve_forever()

# Handles requests
class DataHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    def do_HEAD(dServe):
        dServe.send_response(200)
        dServe.send_header("connection-type", "text/html")
        dServe.end_headers()
    def do_GET(dServe):
        global uri
        dServe.send_response(200)
        dServe.send_header("connection-type", "text/html")
        uri = dServe.path
        dServe.end_headers()
        clientHostname = dServe.address_string()
        clientIP = dServe.connection.getsockname()[0]
        dServe.wfile.write(uri)
    print(uri)
    print(clientHostname)
    print(clientIP)


    # This is what's written to the page:
    uriPar = csv.reader(uri, delimiter='?')
    uriEnt = csv.reader(uriPar[0], delimiter='/')
    sqlConnect = sql.connect(dbFile)
    for entity in uriEnt:
        with sqlConnect:    
            sqlCursor = sqlConnect.cursor()
                if entity[1] == "app":
                    if len(entity) == 3:
                        print clientHostname + " made request for app " + entity[2]
                        sqlCursor.execute("SELECT Executable,Path,Command FROM " + appsTable + " WHERE Latest='true' AND Enabled='true' AND Name='" + entity[2] + "'")
                    else:
                        print clientHostname + " made request for app " + entity[2] + ", specifically version " + entity[3]
                        sqlCursor.execute("SELECT Executable,Path,Command FROM " + appsTable + " WHERE Enabled='true' AND Version='" + entity[3] + "' AND Name='" + entity[2] + "'")
                elif entity[1] == "group":
                    if len(entity) == 3:
                        print clientHostname + " made request for group " + entity[2]
                        sqlCursor.execute("SELECT AppList FROM " + groupsTable + " WHERE Latest='true' AND Enabled='true' AND Name='" + entity[2] + "'")
                    else:
                        print clientHostname + " made request for group " + entity[2] + ", specifically version " + entity[3]
                        sqlCursor.execute("SELECT AppList FROM " + groupsTable + " WHERE Enabled='true' AND Version='" + entity[3] + "' AND Name='" + entity[2] + "'")
    rows = sqlCursor.fetchall()
    for place in rows:
        for position in place:
            dServe.wfile.write(position)
            dServe.wfile.write(",")

# Serves http
if __name__ == '__main__':
    dataServer_class = BaseHTTPServer.HTTPServer
    dataServer = dataServer_class((hostName, dataPort), DataHandler)
    print time.asctime(), "Data Service Starts - %s:%s" % (hostName, dataPort)
    print time.asctime(), "File Service Starts - %s:%s" % (hostName, filePort)
    try:
    fileServerThread = multiprocessing.Process(target=file_serve) 
    fileServerThread.start()  # Starts File Server
        dataServer.serve_forever()  # Starts HTTP Server
    except KeyboardInterrupt:
        pass
    dataServer.server_close()
    fileServer.server_close()
    print time.asctime(), "Server Stops - %s:%s" % (hostName, dataPort)
  • 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-13T10:54:56+00:00Added an answer on June 13, 2026 at 10:54 am

    Fist of all, all the print statements in your code are executed at the time the class definition is loaded, probably not what you really want.

    Second, if this is complete code, you never ever construct and start your HTTP server instance. You need a code more or less like this, it instantiates and starts the server object:

    if __name__ == '__main__':
        httpd = BaseHTTPServer.HTTPServer((HOST_NAME, PORT_NUMBER), DataHandler)
        try:
            httpd.serve_forever()
        except KeyboardInterrupt:
            pass
        httpd.server_close()
    

    Also, using global variables this way is not a good idea – for example, what if your server accepts many connections at the same time?

    If you’re new to Python, I suggest you start playing with existing, working code, e.g. this sample.

    Edit: It seems you have parts of the code incorrectly indented. Look at the following example:

    class Test(object):
    
        def run(self):
            print 1
        print 2
    
    # By this time, '2' is already printed!
    print 3
    t = Test()
    t.run()
    

    It prints out:

    2
    3
    1
    

    The same is going on in your code – print statements and the code following it is indented by 4 spaces, so it will run when the class is being parsed (well, not exactly, simplifying a bit).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I want to construct a data frame in an Rcpp function, but when I
I'm having trouble keeping the paragraph square between the quote marks. In firefox the
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
I want to count how many characters a certain string has in PHP, but
For some reason, after submitting a string like this Jack’s Spindle from a text
I am trying to render a haml file in a javascript response like so:

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.