Issue with importError: no module named BaseHTTPServer - python-2.7

Learning Python 2.7 and trying to run it on Vagrant.
Steps taken:
Vagrant up
Vagrant ssh
Run command python webserver.py
Issue when I run this command, it gives out an ImportError: No module named BaseHTTPServer. Is this problem related to pg_config.sh? Thank you in advance for helping me understand.
I have checked my python 2.7 directory. BaseHTTPServer.py seems to be there.
from BaseHTTPServer import BaseHTTPRequestHandler, BaseHTTPServer
class WebServerHandler(BaseHTTPRequestHandler):
def do_Get(self):
if self.path.endswith("/hello"):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_header()
message = ""
message += "<html><body>Hello!</body></html>"
self.wfile.write(message)
print message
return
else:
self.send_error(404,'File Not Found: %s' % self.path)
def main():
try:
port = 8080
server = HTTPServer(('', port), WebServerHandler)
print "Web Server running on port %s" % port
server.serveforever()
except KeyboardInterrupt:
print " ^C entered, stopping web server...."
server.socket.close()
if _name_ == '__main__':
main()

You may consider switching to python 3.x. This is the updated version of your code in Python 3.7.2. Notice in the code below that the BaseHTTPServer module is changed to http.server in python3 link
from http.server import BaseHTTPRequestHandler, HTTPServer
class WebServerHandler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path.endswith("/hello"):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
message = ""
message += "<html><body>Hello!</body></html>"
self.wfile.write(message)
print (message)
return
else:
self.send_error(404, 'File Not Found: %s' % self.path)
def main():
try:
port = 8080
server = HTTPServer(('', port), WebServerHandler)
print ("Web Server running on port %s" % port)
server.serve_forever()
except KeyboardInterrupt:
print (" ^C entered, stopping web server....")
server.socket.close()
if __name__ == '__main__':
main()
You can follow the link I provided above to read more from the documentation.

Are you sure that the python you are running/testing from the command line is the same python that your script is running?
i.e. BaseHTTPServer might be present in one install, but not the other.
For example, on my machine:
$ which python2.7
/usr/bin/python2.7
Is your "python" (in the command line you specified) the same as "python2.7"?
$ python
Python 2.7.10 (default, Oct 23 2015, 19:19:21)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import BaseHTTPServer
>>> BaseHTTPServer
<module 'BaseHTTPServer' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/BaseHTTPServer.pyc'>
Try a module that does exist to ensure the path is what you are expecting.

In python earlier than v3 you need to run http server as
python -m SimpleHTTPServer 8069

if you are using pycharm, change the interpreter to Python 2.7 from the latest version.
If the project Interpreter is not present you can also add one by specifying the python 2.7 install path.

Related

Python ConfigParser - module object is not callable in Fedora 23

Trying to read an .ini db file from python to test a connection to a PostGres database
Python Version 2.7.11
In Fedora, I installed with
sudo dnf install python-configparser
Install 1 Package
Total download size: 41 k
Installed size: 144 k
Is this ok [y/N]: y
Downloading Packages:
python-configparser-3.5.0b2-0.2.fc23.noarch.rpm 40 kB/s | 41 kB 00:01
Total 31 kB/s | 41 kB 00:01
Running transaction check
Transaction check succeeded.
Running transaction test
Transaction test succeeded.
Running transaction
Installing : python-configparser-3.5.0b2-0.2.fc23.noarch 1/1
Verifying : python-configparser-3.5.0b2-0.2.fc23.noarch 1/1
Installed:
python-configparser.noarch 3.5.0b2-0.2.fc23
in my config.py I do a
import configparser
when I run my script I get 'module' object is not callable
db.ini
[test1]
host=IP address
database=db
port=5432
user=username
password=pswd
[test2]
host=localhost
database=postgres
port=7999
user=abc
password=abcd
config.py
#!/usr/bin/env python
#from configparser import ConfigParser
import configparser
def config(filename='database.ini', section='gr'):
# create a parser
parser = configparser()
# read config file
parser.read(filename)
# get section, default to gr
db = {}
if parser.has_section(section):
params = parser.items(section)
for param in params:
db[param[0]] = param[1]
else:
raise Exception('Section {0} not found in the {1} file'.format(section, filename))
return db
testing.py
#!/usr/bin/env python
import psycopg2
from config import config
def connect():
""" Connect to the PostgreSQL database server """
conn = None
try:
# read connection parameters
params = config()
# connect to the PostgreSQL server
print('Connecting to the PostgreSQL database...')
conn = psycopg2.connect(**params)
# create a cursor
cur = conn.cursor()
# execute a statement
print('PostgreSQL database version:')
cur.execute('SELECT version()')
# display the PostgreSQL database server version
db_version = cur.fetchone()
print(db_version)
# close the communication with the PostgreSQL
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
print('Database connection closed.')
if __name__ == '__main__':
connect()
[root#svr mytest]# ./testing.py
'module' object is not callable
any ideas ?
thank you.
You have an error in your parser creation, see the ConfigParser examples:
An example of reading the configuration file again:
import ConfigParser
config = ConfigParser.RawConfigParser()
config.read('example.cfg')
In Python, a module is basically just a file, so if you want to use anything from this module, you have to specify what from the module you want. In your case, change the lines to
# create a parser
parser = configparser.ConfigParser()
This way, you are using the class ConfigParser from the module.
You can also use the follow to import the parser:
from configparser import ConfigParser
instead of
import configparser
I had the same issue as you and this worked for me.

Sniff error in Scapy

I am trying to use scapy for one of my project. But, it gives the following error, When I test it.
NameError: name 'sniff' is not defined
import sys
from scapy import *
devices = set()
def PacketHandler(pkt):
if pkt.haslayer(Dot11) :
dot11_layer = pkt.getlayer(Dot11)
if dot11_layer.addr2 and ( dot11_layer.addr2 not in devices ):
devices.add(dot11_layer.addr2)
print dot11_layer.addr2
sniff(iface = sys.argv[1], count = int(sys.argv[2]), prn = PacketHandler)
if I change module name to scapy.all, it says there is no module.
Python version: 2.7
Scapy version: 2.3.3
I have just installed with pip install scapy.Any helps would be appreciated.
You must import Scapy as from scapy.all import *, and you must not name your script scapy.py (or any other script in the current directory or your PYTHONPATH)!

How to launch a Python Spyder session through script / shortcut?

I have this code to launch a Spyder IDE, in Anaconda 2, Python 2.7 :
from spyderlib import start_app
main1= start_app.main()
main1.load_session('/project27/_test01_.session.tar')
'''
from spyderlib.utils.iofuncs import load_session
load_session(filename+'.session.tar')
'''
Code method to load session is here: https://github.com/jromang/spyderlib/blob/master/spyderlib/spyder.py
#---- Sessions
def load_session(self, filename=None):
"""Load session"""
if filename is None:
self.redirect_internalshell_stdio(False)
filename, _selfilter = getopenfilename(self, _("Open session"),
getcwd(), _("Spyder sessions")+" (*.session.tar)")
self.redirect_internalshell_stdio(True)
if not filename:
return
if self.close():
self.next_session_name = filename
the 1st part comes from Anaconda Scripts where Spyder script.
It seems not working to load session.
Spyder sessions were removed in Spyder 3.0. Now the same functionality is provided by Projects (which also save the list of open files in the Editor), so please update to that version.
Besides, Spyder 3.1 will come with a new option called --project to load a project at startup (Spyder 3.1 will be released on January 17/2017).
For people still using only Spyder 2.0 (....), there is a small hack possible to create shortcut of session (SPyder session launched directly with shortcut).
Here, the code :
# -*- coding: utf-8 -*-
import sys, time, os
file_session= ''
if len(sys.argv) > 1 :
file_session= sys.argv[1]
print file_session
sys.argv= sys.argv[:1]
from spyderlib import start_app
if file_session != '' :
main1= start_app.main( file_session)
else :
main1= start_app.main()

no module named http.server

here is my web server class :
import http.server
import socketserver
class WebHandler(http.server.BaseHTTPRequestHandler):
def parse_POST(self):
ctype, pdict = cgi.parse_header(self.headers['content-type'])
if ctype == 'multipart/form-data':
postvars = cgi.parse_multipart(self.rfile, pdict)
elif ctype == 'application/x-www-form-urlencoded':
length = int(self.headers['content-length'])
postvars = urllib.parse.parse_qs(self.rfile.read(length),
keep_blank_values=1)
else:
postvars = {}
return postvars
def do_POST(self):
postvars = self.parse_POST()
print(postvars)
# reply with JSON
self.send_response(200)
self.send_header("Content-type", "application/json")
self.send_header("Access-Control-Allow-Origin","*");
self.send_header("Access-Control-Expose-Headers: Access-Control-Allow-Origin");
self.send_header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
self.end_headers()
json_response = json.dumps({'test': 42})
self.wfile.write(bytes(json_response, "utf-8"))
when i run server i got "name 'http' is not defined" after import http.server then i got this "no module named http.server"
In python earlier than v3 you need to run http server as
python -m SimpleHTTPServer 8012
#(8069=portnumber on which your python server is configured)
And for python3
python3 -m http.server 7034 #(any free port number)
http.server only exists in Python 3. In Python 2, you should use the BaseHTTPServer module:
from BaseHTTPServer import BaseHTTPRequestHandler
should work just fine.
like #Sami said: you need earlier versions of python (2.7)
- if you're running on Linux you need to "apt install python-minimal"
- when launching the server "python2 -m SimpleHTTPServer 8082" [or any other port]. By default, python will launch it on 0.0.0.0 which actually is 127.0.0.1:8082 [or your specific port]
Happy hacking
PS when you have 2 versions of python, you need to specify every time you run a command, "python2" or "python3"

uwsgi: no app loaded. going in full dynamic mode

In my uwsgi config, I have these options:
[uwsgi]
chmod-socket = 777
socket = 127.0.0.1:9031
plugins = python
pythonpath = /adminserver/
callable = app
master = True
processes = 4
reload-mercy = 8
cpu-affinity = 1
max-requests = 2000
limit-as = 512
reload-on-as = 256
reload-on-rss = 192
no-orphans
vacuum
My app structure looks like this:
/adminserver
app.py
...
My app.py has these bits of code:
app = Flask(__name__)
...
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5003, debug=True)
The result is that when I try to curl my server, I get this error:
Wed Sep 11 23:28:56 2013 - added /adminserver/ to pythonpath.
Wed Sep 11 23:28:56 2013 - *** no app loaded. going in full dynamic mode ***
Wed Sep 11 23:28:56 2013 - *** uWSGI is running in multiple interpreter mode ***
What do the module and callable options do? The docs say:
module, wsgi Argument: string
Load a WSGI module as the application. The module (sans .py) must be
importable, ie. be in PYTHONPATH.
This option may be set with -w from the command line.
callable Argument: string Default: application
Set default WSGI callable name.
Module
A module in Python maps to a file on disk - when you have a directory like this:
/some-dir
module1.py
module2.py
If you start up a python interpreter while the current working directory is /some-dir you will be able to import each of the modules:
some-dir$ python
>>> import module1, module2
# Module1 and Module2 are now imported
Python searches sys.path (and a few other things, see the docs on import for more information) for a file that matches the name you are trying to import. uwsgi uses Python's import process under the covers to load the module that contains your WSGI application.
Callable
The WSGI PEPs (333 and 3333) specify that a WSGI application is a callable that takes two arguments and returns an iterable that yields bytestrings:
# simple_wsgi.py
# The simplest WSGI application
HELLO_WORLD = b"Hello world!\n"
def simple_app(environ, start_response):
"""Simplest possible application object"""
status = '200 OK'
response_headers = [('Content-type', 'text/plain')]
start_response(status, response_headers)
return [HELLO_WORLD]
uwsgi needs to know the name of a symbol inside of your module that maps to the WSGI application callable, so it can pass in the environment and the start_response callable - essentially, it needs to be able to do the following:
wsgi_app = getattr(simple_wsgi, 'simple_app')
TL;PC (Too Long; Prefer Code)
A simple parallel of what uwsgi is doing:
# Use `module` to know *what* to import
import simple_wsgi
# construct request environment from user input
# create a callable to pass for start_response
# and then ...
# use `callable` to know what to call
wsgi_app = getattr(simple_wsgi, 'simple_app')
# and then call it to respond to the user
response = wsgi_app(environ, start_response)
For anyone else having this problem, if you are sure your configuration is correct, you should check your uWSGI version.
Ubuntu 12.04 LTS provides 1.0.3. Removing that and using pip to install 2.0.4 resolved my issues.
First, check your configuration whether is correct.
my uwsgi.ini configuration:
[uwsgi]
chdir=/home/air/repo/Qiy
uid=nobody
gid=nobody
module=Qiy.wsgi:application
socket=/home/air/repo/Qiy/uwsgi.sock
master=true
workers=5
pidfile=/home/air/repo/Qiy/uwsgi.pid
vacuum=true
thunder-lock=true
enable-threads=true
harakiri=30
post-buffering=4096
daemonize=/home/air/repo/Qiy/uwsgi.log
then use uwsgi --ini uwsgi.ini to run uwsgi.
if not work, you rm -rf the venv directory, and re-initial the venv, and re-try my step.
I re-initial the venv solved my issue, seems the problem is when I pip3 install some packages of requirements.txt, and upgrade the pip, then install uwsgi package. so, I delete the venv, and re-initial my virtual environment.