Getting following error when running python script for web
Traceback (most recent call last):
File "SampleWSTest.py", line 10, in <module>
from web.wsgiserver.ssl_builtin import BuiltinSSLAdapter
File "C:\Python27\lib\site-packages\web\wsgiserver\ssl_builtin.py", line 14, in <module>
from cherrypy import wsgiserver
ImportError: cannot import name wsgiserver
Running on python 2.7.15
import web
import sys
import argparse
import traceback
from web.wsgiserver import CherryPyWSGIServer
from web.wsgiserver.ssl_builtin import BuiltinSSLAdapter
from OpenSSL import SSL
class Healthcheck:
def GET(self):
return 'Yassssssssss !!!!!'
URLS = ('/svc/healthcheck', 'Healthcheck')
CherryPyWSGIServer.ssl_certificate = 'alice.crt'
CherryPyWSGIServer.ssl_private_key = 'alice.key'
if __name__ == '__main__':
CherryPyWSGIServer.ssl_adapter = BuiltinSSLAdapter(CherryPyWSGIServer.ssl_certificate, CherryPyWSGIServer.ssl_private_key)
CherryPyWSGIServer.ssl_adapter.context = SSL.Context(SSL.SSLv23_METHOD)
CherryPyWSGIServer.ssl_adapter.context.set_options(SSL.OP_NO_SSLv3)
CherryPyWSGIServer.ssl_adapter.context.use_certificate_file(CherryPyWSGIServer.ssl_certificate)
CherryPyWSGIServer.ssl_adapter.context.use_privatekey_file(CherryPyWSGIServer.ssl_private_key)
app = web.application(URLS, globals())
app.run()
This started failing after we had to disable ssl 2 and ssl 3 so had to add ssl_adapter but BuiltinSSLAdapter fails with the import.
If any other alternatives please suggest. Basically want to disable ssl 2 and ssl 3 previously we didnt have from web.wsgiserver.ssl_builtin import BuiltinSSLAdapter
from OpenSSL import SSL
CherryPy moved wsgiserver to cheroot in 2017.
http://docs.cherrypy.dev/en/latest/history.html#v9-0-0
So now you need to import it like this:
from cheroot.wsgi import Server as CherryPyWSGIServer
or rename it throughout.
Related
I have the following project structure:
within blog_posts.py I have the following function and router:
# blog_post.py
router = APIRouter(
prefix="/blog",
tags=["blog"]
)
def required_functionality():
return {"message": "Learning FastAPI is important"}
within blog_get.py I also have a router and import the required_functionality function:
# blog_get.py
from blog_posts import required_functionality
router = APIRouter(
prefix="/blog",
tags=["blog"]
)
a = required_functionality()
Finally inside main.py im importing both routers:
# main.py
from router import blog_get, blog_posts
app = FastAPI()
app.include_router(blog_get.router)
app.include_router(blog_posts.router)
If I then run main.py I get the following error:
Traceback (most recent call last):
File "C:\Users\UKGC\PycharmProjects\FastAPI\Routers\main.py", line 6, in <module>
from router import blog_get, blog_posts
File "C:\Users\UKGC\PycharmProjects\FastAPI\Routers\router\blog_get.py", line 4, in <module>
from blog_posts import required_functionality
ModuleNotFoundError: No module named 'blog_posts'
If i then change the import in blog_get.py to:
# blog_get.py
from router.blog_posts import required_functionality
router = APIRouter(
prefix="/blog",
tags=["blog"]
)
a = required_functionality()
and run main.py again I have no issues, however, if I run blog_get.py directly I get the following error:
Traceback (most recent call last):
File "C:\Users\UKGC\PycharmProjects\FastAPI\Routers\router\blog_get.py", line 4, in <module>
from router.blog_posts import required_functionality
ModuleNotFoundError: No module named 'router'
How can I get main.py and blog_get.py to both work? I clearly don't seem to understand python imports properly, can someone explain what I'm missing?
I've tried converting router to a package, I've tried relative imports.
You should use relative imports, not absolute imports
# blog_get.py
from .blog_posts import required_functionality
When you execute main.py, there is no directory on your module search path that contains blog_posts.py. But there is a module router.blog_posts, and blog_get (which tries to import blog_posts) is in the package router as well.
To be able to run both scripts and get them to work I needed to append the 'router' to sys.path when importing from main.py. This is a bit of a hacky solution, im still open to other solutions?
# main.py
from router import blog_get, blog_posts
app = FastAPI()
app.include_router(blog_get.router)
app.include_router(blog_posts.router)
and
# blog_get.py
import os
import sys
fpath = os.path.dirname(__file__)
sys.path.append(fpath)
from blog_posts import required_functionality
router = APIRouter(
prefix="/blog",
tags=["blog"]
)
a = required_functionality()
When I try to import firebase in Thonny I constantly get the error
Traceback (most recent call last):
File "C:\Users\jackl\brhyu.py", line 1, in <module>
import firebase
File "C:\Users\jackl\AppData\Roaming\Python\Python37\site-packages\firebase\__init__.py", line 3
from .async import process_pool
^
SyntaxError: invalid syntax
Any ideas what's wrong? My code is literally just:
import firebase
I have tried commenting the ".async" part out which didn't work.
I have also tried replacing the code in the backend such as replacing
import atexit
from .async import process_pool
from firebase import *
with
import atexit
from .async import process_pool
from .multiprocess_pool import process_pool
from firebase import *
and then replacing
from .firebase_token_generator import FirebaseTokenGenerator
from .decorators import http_connection
from .async import process_pool
from .jsonutil import JSONEncoder
__all__ = ['FirebaseAuthentication', 'FirebaseApplication']
with
import json
from .firebase_token_generator import FirebaseTokenGenerator
from .decorators import http_connection
from .async import process_pool
from .multiprocess_pool import process_pool
from .jsonutil import JSONEncoder
I'm completely stumped...
Any help is greatly appreciated, I need this for a big exam
I have a twisted tac file (twisted_service.py) with a code:
from twisted.application import service
# application.py file in the same dir
from .application import setup_reactor
class WebsocketService(service.Service):
def startService(self):
service.Service.startService(self)
setup_reactor()
application = service.Application("ws")
ws_service = WebsocketService()
ws_service.setServiceParent(application)
Here is application.py file, which sets up the reactor:
# -*- coding: utf-8 -*-
from twisted.web.server import Site
from twisted.web.static import Data
from twisted.internet import reactor, defer
from autobahn.twisted.resource import WebSocketResource
from autobahn.twisted.websocket import WebSocketServerFactory
from txsni.snimap import SNIMap
from txsni.maputils import Cache
from txsni.snimap import HostDirectoryMap
from twisted.python.filepath import FilePath
from tools.database.async import pg_conn
from tools.database import makedsn
from tools.config import main_db
from tools.modules.external import flask_setup
import tools.config as config
import websockethandlers as wsh
from pytrapd import TrapsListener
PROTOCOLMAP = {
'portcounters': wsh.PortCounters,
'eqcounters': wsh.EquipmentCounters,
'settings': wsh.Settings,
'refresh': wsh.Refresher,
'montraps': wsh.TrapsMonitoring,
'fdbs': wsh.FdbParser,
'portstate': wsh.PortState,
'cable': wsh.CableDiagnostic,
'eqcable': wsh.EquipmentCableDiagnostic,
'igmp': wsh.Igmp,
'ipmac': wsh.IpMac,
'lldp': wsh.LLDPParser,
'alias': wsh.AliasSetup,
'ping': wsh.Ping
}
#defer.inlineCallbacks
def setup_reactor():
flask_setup()
yield pg_conn.connect(makedsn(main_db))
root = Data("", "text/plain")
for key in PROTOCOLMAP:
factory = WebSocketServerFactory("wss://localhost:%s" % config.ws_port)
factory.protocol = PROTOCOLMAP[key]
resource = WebSocketResource(factory)
root.putChild(key, resource)
site = Site(root)
context_factory = SNIMap(
Cache(HostDirectoryMap(FilePath(config.certificates_directory)))
)
reactor.listenSSL(config.ws_port, site, context_factory)
traps_listener = TrapsListener()
traps_listener.listen_traps(config.trap_ip)
traps_listener.listen_messages(config.fifo_file)
if __name__ == '__main__':
setup_reactor()
import sys
from twisted.python import log
log.startLogging(sys.stdout)
reactor.run()
I use twistd -noy twisted_service.py command to run the twisted service. It has been working for twisted 16.3.2 version. After upgrade to any next version I got the error:
Unhandled Error
Traceback (most recent call last):
File "/home/kalombo/.virtualenvs/dev/local/lib/python2.7/site-packages/twisted/application/app.py", line 662, in run
runApp(config)
File "/home/kalombo/.virtualenvs/dev/local/lib/python2.7/site-packages/twisted/scripts/twistd.py", line 25, in runApp
_SomeApplicationRunner(config).run()
File "/home/kalombo/.virtualenvs/dev/local/lib/python2.7/site-packages/twisted/application/app.py", line 380, in run
self.application = self.createOrGetApplication()
File "/home/kalombo/.virtualenvs/dev/local/lib/python2.7/site-packages/twisted/application/app.py", line 445, in createOrGetApplication
application = getApplication(self.config, passphrase)
--- <exception caught here> ---
File "/home/kalombo/.virtualenvs/dev/local/lib/python2.7/site-packages/twisted/application/app.py", line 456, in getApplication
application = service.loadApplication(filename, style, passphrase)
File "/home/kalombo/.virtualenvs/dev/local/lib/python2.7/site-packages/twisted/application/service.py", line 412, in loadApplication
application = sob.loadValueFromFile(filename, 'application')
File "/home/kalombo/.virtualenvs/dev/local/lib/python2.7/site-packages/twisted/persisted/sob.py", line 177, in loadValueFromFile
eval(codeObj, d, d)
File "twisted_service.py", line 3, in <module>
from .application import setup_reactor
exceptions.ImportError: No module named application
How should I run the twisted or import module properly?
What the answer I found nearly yours. like the follows:
import os
import sys
sys.path = [os.path.join(os.getcwd(), '.'), ] + sys.path
just add the current working directory to the sys.path.
But I have not found more better method.... I think this not very good.
I found the answer here http://twistedmatrix.com/pipermail/twisted-python/2016-September/030783.html
It is a new feature in Twisted 16.4.0. In previous versions twistd script automatically added working dir to system paths, from 16.4.0 version i have to added it manually. It can be added something like this in twisted_service.py file:
import os
import sys
TWISTED_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(TWISTED_DIR)
I wrote a python script to have a soap server with flask, it's exactly like what the documentation says:
from time import ctime
from flask import Flask
from flaskext.enterprise import Enterprise
if __name__ == '__main__':
app = Flask(__name__)
enterprise = Enterprise(app)
class DemoService(enterprise.SOAPService):
#enterprise.soap(_returns=enterprise._sp.String)
def get_time(self):
return ctime()
But when I run the program, it says:
Traceback (most recent call last):
File "D:/Workspace/src/flask_soap_server.py", line 3, in <module>
from flaskext.enterprise import Enterprise
File "C:\Python27\lib\site-packages\flaskext\enterprise.py", line 20, in <module>
from soaplib.core import Application
ImportError: No module named core
I also wrote a client to call this server's WSDL address:
from flaskext.enterprise import Enterprise
from flask import Flask
if __name__ == '__main__':
app = Flask(__name__)
enterprise = Enterprise(app)
client = enterprise.connect_to_soap_service('http://192.168.20.232:8000/_enterprise/soap?wsdl')
#app.route('/time')
def index():
time = client.service.get_time()
Soaplib (https://github.com/soaplib/soaplib):
This project is discontinued. Please head over to
github.com/arskom/spyne for the next version.
Flask Enterprise (https://pypi.python.org/pypi/Flask-Enterprise): latest release in 2011
Maybe it's time to move on to a better supported projects :)
There is a Spyne + Flask example: https://github.com/arskom/spyne/tree/master/examples/flask
I have installed pysnmp-4.x.I am getting following error during running a SNMP program.
I am using pysnmpSE 3.5.2 now but getting same error. I found that pysnmpSE doesn't hav v4 module. I was suggested that following error should resolved if pySNMP SE 3.x is used.
Traceback (most recent call last):
File "C:\Documents and Settings\ggne0622\Desktop\Python\google-python-exercises\babynames\SimpleAgent.py", line 18, in <module>
from twistedsnmp import agent, agentprotocol, bisectoidstore
File "C:\Python27\Lib\site-packages\twistedsnmp\agent.py", line 4, in <module>
from twistedsnmp import datatypes
File "C:\Python27\Lib\site-packages\twistedsnmp\datatypes.py", line 7, in <module>
from twistedsnmp.pysnmpproto import v2c,v1
File "C:\Python27\Lib\site-packages\twistedsnmp\pysnmpproto.py", line 13, in <module>
from pysnmp.v4.proto.omni import v2c,v1, error, rfc1157, rfc1905
ImportError: No module named v4.proto.omni
Code:
#!/usr/bin/env python
from twisted.internet.iocpreactor import reactor
from twisted.internet import error as twisted_error
from twistedsnmp import agent, agentprotocol, bisectoidstore
#from twisted.internet import interfaces
try:
from twistedsnmp import bsdoidstore
except ImportError:
import warnings
warnings.warn( """No BSDDB OID Storage available for testing""" )
bsdoidstore = None
def createAgent( oids ):
ports = [161]+range(20000,25000)
for port in ports:
try:
`agentObject = reactor.IOCPReactor.listenUDP(port,` `agentprotocol.AgentProtocol(snmpVersion = 'v2c',agent = agent.Agent(dataStore =` `bisectoidstore.BisectOIDStore(OIDs = oids,),),),)`
`except twisted_error.CannotListenError:`
`pass`
`else:`
`return agentObject, port`
testingOIDs = {
'.1.3.6.1.2.1.1.1.0': 'Some tool out in the field',
'.1.3.6.1.2.1.1.2.0': '.1.3.6.1.4.1.88.3.1',
'.1.3.6.1.2.1.1.3.0': 558566090,
'.1.3.6.1.2.1.1.4.0': "support#somewhere.ca",
'.1.3.6.1.2.1.1.5.0': "NameOfSystem",
'.1.3.6.1.2.1.1.6.0': "SomeHeadEnd, West Hinterlands, Canada",
}
def main(oids=testingOIDs):
agent, port = createAgent( oids )
if __name__ == "__main__":
reactor.IOCPReactor.callWhenRunning( main )
reactor.IOCPReactor.run()
TwistedSNMP does not seem to be designed to work with PySNMP 4.x. Thus you should either use PySNMP 3.x / PySNMP SE or switch to PySNMP 4.x which has its own Twisted binding.