I am attempting to resolve the following error:
asyncpg.exceptions._base.InterfaceError: cannot perform operation: another operation is in progress
Here is the full traceback:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/Users/ddd/.pyenv/versions/3.8.6/lib/python3.8/multiprocessing/spawn.py", line 116, in spawn_main
exitcode = _main(fd, parent_sentinel)
│ │ └ 4
│ └ 7
└ <function _main at 0x109c8aca0>
File "/Users/ddd/.pyenv/versions/3.8.6/lib/python3.8/multiprocessing/spawn.py", line 129, in _main
return self._bootstrap(parent_sentinel)
│ │ └ 4
│ └ <function BaseProcess._bootstrap at 0x109b1f8b0>
└ <SpawnProcess name='SpawnProcess-4' parent=36604 started>
File "/Users/ddd/.pyenv/versions/3.8.6/lib/python3.8/multiprocessing/process.py", line 315, in _bootstrap
self.run()
│ └ <function BaseProcess.run at 0x109b18ee0>
└ <SpawnProcess name='SpawnProcess-4' parent=36604 started>
File "/Users/ddd/.pyenv/versions/3.8.6/lib/python3.8/multiprocessing/process.py", line 108, in run
self._target(*self._args, **self._kwargs)
│ │ │ │ │ └ {'config': <uvicorn.config.Config object at 0x109cd55b0>, 'target': <bound method Server.run of <uvicorn.server.Server object...
│ │ │ │ └ <SpawnProcess name='SpawnProcess-4' parent=36604 started>
│ │ │ └ ()
│ │ └ <SpawnProcess name='SpawnProcess-4' parent=36604 started>
│ └ <function subprocess_started at 0x10a4aca60>
└ <SpawnProcess name='SpawnProcess-4' parent=36604 started>
File "/Users/ddd/Desktop/repos/xxx/.venv/lib/python3.8/site-packages/uvicorn/subprocess.py", line 61, in subprocess_started
target(sockets=sockets)
│ └ [<socket.socket fd=3, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('0.0.0.0', 80)>]
└ <bound method Server.run of <uvicorn.server.Server object at 0x109cd56a0>>
File "/Users/ddd/Desktop/repos/xxx/.venv/lib/python3.8/site-packages/uvicorn/server.py", line 48, in run
loop.run_until_complete(self.serve(sockets=sockets))
│ │ │ │ └ [<socket.socket fd=3, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('0.0.0.0', 80)>]
│ │ │ └ <function Server.serve at 0x10a4abca0>
│ │ └ <uvicorn.server.Server object at 0x109cd56a0>
│ └ <function BaseEventLoop.run_until_complete at 0x10a205820>
└ <_UnixSelectorEventLoop running=True closed=False debug=False>
File "/Users/ddd/.pyenv/versions/3.8.6/lib/python3.8/asyncio/base_events.py", line 603, in run_until_complete
self.run_forever()
│ └ <function BaseEventLoop.run_forever at 0x10a205790>
└ <_UnixSelectorEventLoop running=True closed=False debug=False>
File "/Users/ddd/.pyenv/versions/3.8.6/lib/python3.8/asyncio/base_events.py", line 570, in run_forever
self._run_once()
│ └ <function BaseEventLoop._run_once at 0x10a209310>
└ <_UnixSelectorEventLoop running=True closed=False debug=False>
File "/Users/ddd/.pyenv/versions/3.8.6/lib/python3.8/asyncio/base_events.py", line 1859, in _run_once
handle._run()
│ └ <function Handle._run at 0x10a13ed30>
└ <Handle <TaskWakeupMethWrapper object at 0x10bb75a60>(<_GatheringFu...in progress')>)>
File "/Users/ddd/.pyenv/versions/3.8.6/lib/python3.8/asyncio/events.py", line 81, in _run
self._context.run(self._callback, *self._args)
│ │ │ │ │ └ <member '_args' of 'Handle' objects>
│ │ │ │ └ <Handle <TaskWakeupMethWrapper object at 0x10bb75a60>(<_GatheringFu...in progress')>)>
│ │ │ └ <member '_callback' of 'Handle' objects>
│ │ └ <Handle <TaskWakeupMethWrapper object at 0x10bb75a60>(<_GatheringFu...in progress')>)>
│ └ <member '_context' of 'Handle' objects>
└ <Handle <TaskWakeupMethWrapper object at 0x10bb75a60>(<_GatheringFu...in progress')>)>
> File "./xxx/xxx/xxx.py", line 144, in get_disclosure_data
hh_json, db_json = await asyncio.gather(*coroutines)
│ │ └ [<coroutine object xxxx at 0x10bb2cb40>, <coroutine object db_call at 0x10bb2cc40>]
│ └ <function gather at 0x10a1fad30>
└ <module 'asyncio' from '/Users/ddd/.pyenv/versions/3.8.6/lib/python3.8/asyncio/__init__.py'>
File "./xxx/xxx/xxx.py", line 52, in db_call
db_json = await asyncio.gather(*coroutines, loop=asyncio.get_event_loop())
│ │ │ │ └ <built-in function get_event_loop>
│ │ │ └ <module 'asyncio' from '/Users/ddd/.pyenv/versions/3.8.6/lib/python3.8/asyncio/__init__.py'>
│ │ └ [<coroutine object DBConnectionManager.fetch_item at 0x10bb434c0>, <coroutine object DBConnectionManager.fetch_item at 0x10bb...
│ └ <function gather at 0x10a1fad30>
└ <module 'asyncio' from '/Users/ddd/.pyenv/versions/3.8.6/lib/python3.8/asyncio/__init__.py'>
File "./xxx/xxx/xx.py", line 97, in fetch_item
await self._connection_pool.release(self.con)
│ │ │ │ └ <PoolConnectionProxy [released] 0x10bbc9cd0>
│ │ │ └ <chd_api.data.db.DBConnectionManager object at 0x10b946a30>
│ │ └ <function Pool.release at 0x10b956a60>
│ └ <asyncpg.pool.Pool object at 0x10bb131e0>
└ <chd_api.data.db.DBConnectionManager object at 0x10b946a30>
File "/Users/ddd/Desktop/repos/xxx/.venv/lib/python3.8/site-packages/asyncpg/pool.py", line 666, in release
return await asyncio.shield(ch.release(timeout))
│ │ │ │ └ None
│ │ │ └ <function PoolConnectionHolder.release at 0x10b952e50>
│ │ └ <asyncpg.pool.PoolConnectionHolder object at 0x10bb2a5c0>
│ └ <function shield at 0x10a1faee0>
└ <module 'asyncio' from '/Users/ddd/.pyenv/versions/3.8.6/lib/python3.8/asyncio/__init__.py'>
File "/Users/ddd/Desktop/repos/xxx/.venv/lib/python3.8/site-packages/asyncpg/pool.py", line 218, in release
raise ex
File "/Users/ddd/Desktop/repos/xxx/.venv/lib/python3.8/site-packages/asyncpg/pool.py", line 208, in release
await self._con.reset(timeout=budget)
│ │ └ None
│ └ <member '_con' of 'PoolConnectionHolder' objects>
└ <asyncpg.pool.PoolConnectionHolder object at 0x10bb2a5c0>
File "/Users/ddd/Desktop/repos/xxx/.venv/lib/python3.8/site-packages/asyncpg/connection.py", line 1311, in reset
await self.execute(reset_query, timeout=timeout)
│ │ │ └ None
│ │ └ 'SELECT pg_advisory_unlock_all();\nCLOSE ALL;\nUNLISTEN *;\nRESET ALL;'
│ └ <function Connection.execute at 0x10b93f3a0>
└ <asyncpg.connection.Connection object at 0x10bc34120>
File "/Users/ddd/Desktop/repos/xxx/.venv/lib/python3.8/site-packages/asyncpg/connection.py", line 297, in execute
return await self._protocol.query(query, timeout)
│ │ │ └ None
│ │ └ 'SELECT pg_advisory_unlock_all();\nCLOSE ALL;\nUNLISTEN *;\nRESET ALL;'
│ └ <member '_protocol' of 'Connection' objects>
└ <asyncpg.connection.Connection object at 0x10bc34120>
File "asyncpg/protocol/protocol.pyx", line 321, in query
self._check_state()
File "asyncpg/protocol/protocol.pyx", line 684, in asyncpg.protocol.protocol.BaseProtocol._check_state
raise apg_exc.InterfaceError(
│ └ <class 'asyncpg.exceptions._base.InterfaceError'>
└ <module 'asyncpg.exceptions' from '/Users/ddd/Desktop/repos/chd-api/.venv/lib/python3.8/site-packages/asyncpg/exception...
asyncpg.exceptions._base.InterfaceError: cannot perform operation: another operation is in progress
where I have the following code to set up a connection pool and execute queries with connections in the pool:
class DBConnectionManager(object):
""" Class for setting up and tearing down db connection """
def __init__(self):
self.host = SETTINGS.db_host
self.database = SETTINGS.db_name
self.user = SETTINGS.db_user
self.password = SETTINGS.db_password
self.port = "5432"
self._connection_pool = None
self.con = None
async def connect(self):
if not self._connection_pool:
try:
self._connection_pool = await asyncpg.create_pool(
host=self.host,
database=self.database,
user=self.user,
password=self.password,
port=self.port,
min_size=50,
max_size=100,
)
logger.info("Database pool connection opened")
except Exception as e:
logger.exception(e)
async def fetch_item(self, query: str, *args):
if not self._connection_pool:
await self.connect()
else:
self.con = await self._connection_pool.acquire()
try:
result = await self.con.fetch(query, *args)
return result
except Exception as e:
logger.exception(e)
finally:
await self._connection_pool.release(self.con)
async def close(self):
if not self._connection_pool:
try:
await self._connection_pool.close()
logger.info("Database pool connection closed")
except Exception as e:
logger.exception(e)
and am attempting to execute some 22 database calls using the following:
async def db_call(db, lat, lng):
"""
Performs the necessary db calls given a lat, lng
Required Input:
lat::float a latitude in decimal degrees. Must be specified with `lng` (i.e. 39.2994)
lng::float a longitude in decimal degrees. Must be specified with `lat` (i.e. -122.33)
Returns:
dict
"""
coroutines = []
for table in db_map:
# SQL columns
db_fields = ",".join(
[
f"{col} AS {db_map[table]['fields'][col]}"
for col in db_map[table]["fields"]
]
)
# Output names
api_fields = [db_map[table]["fields"][col] for col in db_map[table]["fields"]]
if db_map[table]["query_type"] == "pip":
limit = db_map[table]["options"]["LIMIT"]
query = f"SELECT {db_fields} from {table} WHERE (ST_Covers(geom, GeomFromEWKT('SRID=4326;POINT({lng} {lat})'))) LIMIT {limit};"
else:
distance = db_map[table]["options"]["DISTANCE"]
geo2geo = f"geom::geography, GeomFromEWKT('SRID=4326;POINT({lng} {lat})')::geography"
query = (
f"SELECT {db_fields}, ST_Distance({geo2geo})"
f"from {table} WHERE (ST_DWithin({geo2geo}, {distance}))"
f"ORDER BY ST_Distance({geo2geo}) LIMIT 1;"
)
coroutines.append(db.fetch_item(query))
db_res = await asyncio.gather(*coroutines)
.... code for processing results
I have examined several issues on the asyncpg github concerning this error and am still not finding an appropriate solution. Note also, this call is being performed in FastAPI. Any guidance would be appreciated on why this error may be occurring/steps to resolve it.
The assignment to self.con in fetch_item causes multiple coroutines to share the same connection. While you do want them to share the connection pool, sharing the same connection doesn't make sense, as the connection is stateful.
To resolve the issue, replace usage of self.con with a local variable con.
Slightly off topic, but Google often leads to this answer. If you are using SQLAlchemy: Fixed by setting poolclass=NullPool in create_async_engine
Related
I know many similar questions have been asked, but I feel like I've tried everything and I keep getting the same error. I followed this article https://gehrcke.de/2014/02/distributing-a-python-command-line-application/ and I think I've done the same. Anyway, here's my project structure:
nc-textmanager-tool/
├── nc_textmanager
│ ├── gui/
│ ├── textmanager/
│ ├── __init__.py
│ ├── __main__.py
│ └── nc_main.py
├── LICENSE
├── bundles.yaml
├── env.yaml
├── requirements.txt
├── README.rst
└── setup.py
And here's the content of setup.py
import setuptools
with open("README.md", "r", encoding="utf-8") as f:
long_desc = f.read()
with open("requirements.txt", "r", encoding="utf-8") as f:
requirements = f.readlines()
setuptools.setup(
name="nc-textmanager",
version="1.1.11",
author="XXX",
author_email="XXX",
description="A simple tool for viewing and searching through keys and values used by TextManger in NC projects.",
long_description=long_desc,
long_description_content_type="text/markdown",
packages=setuptools.find_packages(),
entry_points={
"console_scripts": ['nc_textmanager = nc_textmanager.nc_main:run']
},
url="???",
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
python_requires='>=3.8',
install_requires=requirements
)
Installing it by running python .\setup.py install works fine, but when I try to run my nc_textmanager script from the console, I get this error:
> nc_textmanager
Traceback (most recent call last):
File "C:\Users\SEHE\AppData\Local\Programs\Python\Python39\Scripts\nc_textmanager-script.py", line 33, in <module>
sys.exit(load_entry_point('nc-textmanager==1.1.11', 'console_scripts', 'nc_textmanager')())
File "C:\Users\SEHE\AppData\Local\Programs\Python\Python39\Scripts\nc_textmanager-script.py", line 25, in importlib_load_entry_point
return next(matches).load()
File "C:\Users\SEHE\AppData\Local\Programs\Python\Python39\lib\importlib\metadata.py", line 77, in load
module = import_module(match.group('module'))
File "C:\Users\SEHE\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'nc_textmanager.nc_main'
I did try to put the nc_textmanager-script.py file in my project root and execute it there, and everything works fine. I'm thus thinking there's an issue with the working directory...
Using python 3.8 on Windows 10.
I have got a problem with circular imports in Python 3.9.
I know there are numerous articles, questions and answers about this topic and I really have read a lot of them and about how to circumvent but I cannot figure out why it happens in my case. As far as I have understood one can circumvent circular imports by doing absolute imports:
This is my Stacktrace:
partially initialized module 'myproject.myapp.service.linepattern.corner' has no attribute 'Corner' (most likely due to a circular import)
File "/mnt/d/User/Programming/MyProject/myproject/myapp/service/linepattern/line.py", line 8, in Line
def __init__(self, cornerRight: cc.Corner, cornerLeft: cc.Corner) -> None:
File "/mnt/d/User/Programming/MyProject/myproject/myapp/service/linepattern/line.py", line 7, in <module>
class Line(ABC):
File "/mnt/d/User/Programming/MyProject/myproject/myapp/service/linepattern/corner.py", line 2, in <module>
import myproject.myapp.service.linepattern.line as cl
File "/mnt/d/User/Programming/MyProject/myproject/myapp/service/linepattern/cornermanager.py", line 2, in <module>
import myproject.myapp.service.linepattern.corner as cc
File "/mnt/d/User/Programming/MyProject/myproject/tests/myapp/test_cornermanager.py", line 3, in <module>
import myproject.myapp.service.linepattern.cornermanager as cm
and this is my file hierarchy
/mnt/d/User/Programming/MyProject
├── manage.py
├── myproject
│ ├── myapp
│ │ ├── __init__.py
│ │ ├── service
│ │ │ └── linepattern
│ │ │ ├── cornermanager.py
│ │ │ ├── corner.py
│ │ │ ├── line.py
│ │ │ ├── __init__.py
│ ├── settings.py
│ ├── tests
│ │ ├── myapp
│ │ │ ├── __init__.py
│ │ │ └── test_cornermanager.py
and finally my code
cornermanager.py
import myproject.myapp.service.linepattern.corner as cc
class CornerManager:
def __init__(self) -> None:
self.cornerList: List[cc.Corner]
for i in range(1, 2):
self.cornerList.append(cc.Corner(i, self))
for corner in self.cornerList:
corner.initializeLines()
def corner(self, cornerNr: int) -> cc.Corner:
return self.cornerList[cornerNr - 1]
corner.py
import myproject.myapp.service.linepattern.cornermanager as cm
import myproject.myapp.service.linepattern.line as cl
class Corner:
def __init__(self, cornerNumber: int, cornerManager: cm.CornerManager) -> None:
self.cornerNumber = cornerNumber
self.cornerManager = cornerManager
self.lineSet: Set[cl.Line]
def initializeLines(self) -> None:
#Add lines to the corner including its neighbor
if self.cornerNumber == 1:
self.lineSet.add(cl.Line(self, self.cornerManager.corner(2)))
elif self.cornerNumber == 2:
self.lineSet.add(cl.Line(self, self.cornerManager.corner(2)))
def addLine(self, line: cl.Line) -> None:
#Remove line from both corners
for corner in cl.cornerPair():
corner.lineSet.add(line)
def removeLine(self, line: cl.Line) -> None:
#Remove line from both corners
for corner in cl.cornerPair():
corner.lineSet.remove(line)
line.py
import myproject.myapp.service.linepattern.corner as cc
class Line:
def __init__(self, cornerRight: cc.Corner, cornerLeft: cc.Corner) -> None:
self.rightCorner = cornerRight
self.leftCorner = cornerLeft
def cornerPair(self) -> Tuple[cc.Corner, cc.Corner]:
#Return both corners
return (self.rightCorner, self.leftCorner)
With the code you put in the question (three separated modules), by including the following code at the top of each file should be able to fix the problems:
from __future__ import annotations
In short this code will treat annotations as strings. You can read more about this at: Type hint of the enclosing class and Evaluation of annotations.
For the errors, this actually how Python executes your modules (start from cornermanager.py):
import corner. With this Python first saves the module in its internal module (sys.modules) before running the imported module code.
In corner.py itself, the first two lines are import statement, so let's start with import cornermanager. Again, Python saves the module in its internal module then executes the code in cornermanager.
Back to cornermanager.py. As we know first line of this module is import corner, but because Python already saved this module (corner) in its internal module, it doesn't import it the second time. That is, Python skips it and executes code below this line. Interestingly, because corner hasn't executed all its code but the first line (import cornermanager), attempt to fetch its Corner class will not succeed.
I have been trying to organize my file structure in my flask app (the current structure is):
├───.git
├───.vscode
├───env
├───src
├─── __init__.py
├─── site.db
│ ├───main
│ │ └───__pycache__
│ │ └─── routes.py
│ │ └─── __init__.py
│ ├───posts
│ │ └───__pycache__
│ │ └─── routes.py
│ │ └─── __init__.py
│ │ └─── forms.py
│ │ └─── utils.py
│ ├───static
│ │ ├───css
│ │ ├───js
│ │ └───profile_pics
│ ├───templates
│ │ └─── ...
│ ├───users
│ │ └─── routes.py
│ │ └─── __init__.py
│ │ └─── forms.py
│ │ └─── utils.py
├───run.py
The site.db file for some reason is empty even though my __init__.py file has "db.create_all()"...
Although, I am getting this error when I try and request the index.html page
[2020-07-16 11:54:38,819] ERROR in app: Exception on / [GET]
Traceback (most recent call last):
File "C:\Users\Owner\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sqlalchemy\engine\base.py", line 1277, in _execute_context
self.dialect.do_execute(
File "C:\Users\Owner\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sqlalchemy\engine\default.py", line 593, in do_execute
cursor.execute(statement, parameters)
sqlite3.OperationalError: no such table: post
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Owner\AppData\Local\Programs\Python\Python38-32\lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\Owner\AppData\Local\Programs\Python\Python38-32\lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\Owner\AppData\Local\Programs\Python\Python38-32\lib\site-packages\flask\app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\Owner\AppData\Local\Programs\Python\Python38-32\lib\site-packages\flask\_compat.py",
line 39, in reraise
raise value
File "C:\Users\Owner\AppData\Local\Programs\Python\Python38-32\lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\Owner\AppData\Local\Programs\Python\Python38-32\lib\site-packages\flask\app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\Owner\OneDrive\code\CloneBook\src\main\routes.py", line 13, in home
posts = Post.query.order_by(
File "C:\Users\Owner\AppData\Local\Programs\Python\Python38-32\lib\site-packages\flask_sqlalchemy\__init__.py", line 496, in paginate
items = self.limit(per_page).offset((page - 1) * per_page).all()
File "C:\Users\Owner\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sqlalchemy\orm\query.py", line 3341, in all
return list(self)
File "C:\Users\Owner\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sqlalchemy\orm\query.py", line 3503, in __iter__
return self._execute_and_instances(context)
File "C:\Users\Owner\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sqlalchemy\orm\query.py", line 3528, in _execute_and_instances
result = conn.execute(querycontext.statement, self._params)
File "C:\Users\Owner\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sqlalchemy\engine\base.py", line 1014, in execute
return meth(self, multiparams, params)
File "C:\Users\Owner\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sqlalchemy\sql\elements.py", line 298, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "C:\Users\Owner\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sqlalchemy\engine\base.py", line 1127, in _execute_clauseelement
ret = self._execute_context(
File "C:\Users\Owner\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sqlalchemy\engine\base.py", line 1317, in _execute_context
self._handle_dbapi_exception(
File "C:\Users\Owner\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sqlalchemy\engine\base.py", line 1511, in _handle_dbapi_exception
util.raise_(
File "C:\Users\Owner\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sqlalchemy\util\compat.py", line 178, in raise_
raise exception
File "C:\Users\Owner\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sqlalchemy\engine\base.py", line 1277, in _execute_context
self.dialect.do_execute(
File "C:\Users\Owner\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sqlalchemy\engine\default.py", line 593, in do_execute
cursor.execute(statement, parameters)
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: post
[SQL: SELECT post.id AS post_id, post.title AS post_title, post.date_posted AS post_date_posted, post.content AS post_content, post.user_id AS post_user_id
FROM post ORDER BY post.date_posted DESC
LIMIT ? OFFSET ?]
Your code is most likely doing the db.create_all() before models have been imported (from whatever file they're in, since you don't have any models.py files). Importing models has the side-effect of registering them.
I am trying to run Gatling with Taurus to experiment with it but it is not working as easily as expected.
I have this code:
execution:
- executor: gatling
scenario: sample
scenarios:
sample:
script: tests/gatling/BasicSimulation.scala
simulation: tests.gatling.BasicSimulation
And using this gatling simulation scala code:
package tests.gatling
import io.gatling.core.Predef._
import io.gatling.http.Predef._
import scala.concurrent.duration._
class BasicSimulation extends Simulation {
val httpConf = http
.baseURL("http://computer-database.gatling.io")
.acceptHeader("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
.doNotTrackHeader("1")
.acceptLanguageHeader("en-US,en;q=0.5")
.acceptEncodingHeader("gzip, deflate")
.userAgentHeader("Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0")
val scn = scenario("BasicSimulation")
.exec(http("request_1")
.get("/"))
.pause(1)
setUp(
scn.inject(atOnceUsers(1))
).protocols(httpConf)
}
When I run it wih this:
bzt gatling.yml
It ends in error with:
08:13:02 ERROR: Child Process Error: Gatling tool exited with non-zero code: 1
...
Gatling STDERR:
Exception in thread "main" io.gatling.core.session.el.ElParserException: Failed to parse text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 with error '[B cannot be cast to [C'
at io.gatling.core.session.el.ElCompiler.parseEl(ElCompiler.scala:249)
at io.gatling.core.session.el.ElCompiler$.parse(ElCompiler.scala:171)
at io.gatling.core.session.el.ElCompiler$.compile(ElCompiler.scala:174)
at io.gatling.core.session.el.package$El$.el$extension(package.scala:26)
at io.gatling.core.ValidationImplicits.stringToExpression(ValidationImplicits.scala:48)
at io.gatling.core.ValidationImplicits.stringToExpression$(ValidationImplicits.scala:48)
at io.gatling.core.Predef$.stringToExpression(Predef.scala:22)
at tests.gatling.BasicSimulation.<init>(BasicSimulation.scala:12)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:488)
at java.base/java.lang.Class.newInstance(Class.java:558)
at io.gatling.app.Runner.run0(Runner.scala:79)
at io.gatling.app.Runner.run(Runner.scala:64)
at io.gatling.app.Gatling$.start(Gatling.scala:59)
at io.gatling.app.Gatling$.fromArgs(Gatling.scala:43)
at io.gatling.app.Gatling$.main(Gatling.scala:35)
at io.gatling.app.Gatling.main(Gatling.scala)
...
I faced the same issue a while ago and root cause was that I was using a jdk 9 , I downgraded to 8 and it worked.
I tried with your code and it works for me on jdk 8
I cannot reproduce your issue using latest Taurus v1.12.1
dt#aldan:/tmp> bzt gatling.yml
09:32:29 INFO: Taurus CLI Tool v1.12.1
09:32:29 INFO: Starting with configs: ['gatling.yml']
09:32:29 INFO: Configuring...
09:32:29 INFO: Artifacts dir: /tmp/2018-08-21_09-32-29.122174
09:32:29 INFO: Preparing...
09:32:30 INFO: Starting...
09:32:30 INFO: Waiting for results...
09:32:31 INFO: Waiting for finish...
09:32:43 WARNING: Please wait for graceful shutdown...
09:32:43 INFO: Shutting down...
09:32:43 INFO: Post-processing...
09:32:43 INFO: Test duration: 0:00:13
09:32:43 INFO: Samples count: 2, 0.00% failures
09:32:43 INFO: Average times: total 0.065, latency 0.000, connect 0.000
09:32:43 INFO: Percentiles:
┌───────────────┬───────────────┐
│ Percentile, % │ Resp. Time, s │
├───────────────┼───────────────┤
│ 0.0 │ 0.045 │
│ 50.0 │ 0.045 │
│ 90.0 │ 0.085 │
│ 95.0 │ 0.085 │
│ 99.0 │ 0.085 │
│ 99.9 │ 0.085 │
│ 100.0 │ 0.085 │
└───────────────┴───────────────┘
09:32:43 INFO: Request label stats:
┌──────────────────────┬────────┬─────────┬────────┬───────┐
│ label │ status │ succ │ avg_rt │ error │
├──────────────────────┼────────┼─────────┼────────┼───────┤
│ request_1 │ OK │ 100.00% │ 0.085 │ │
│ request_1 Redirect 1 │ OK │ 100.00% │ 0.045 │ │
└──────────────────────┴────────┴─────────┴────────┴───────┘
09:32:43 INFO: Artifacts dir: /tmp/2018-08-21_09-32-29.122174
09:32:43 INFO: Done performing with code: 0
dt#aldan:/tmp>
Other environment details:
Gatling: 2.3.0 (downloaded automatically by Taurus)
Java SE 1.8.0_151
First of all try upgrading Taurus to the latest version like:
pip install --upgrade bzt
If it doesn't help you can try building Gatling script from YAML config, check out How to Load Test with Gatling and Taurus guide for more details
Why would I receive a ModuleNotFoundError: No module named 'helpers' when I execute the command prompt script after running pip3 install . from my package's root directory? The location of helpers is c:\users\username\appdata\local\programs\python\python36-32\lib\site-packages\mypackage\helpers.py so how to I get the program to look there?
PS C:\> mypackage
Traceback (most recent call last):
File "C:\Users\username\AppData\Local\Programs\Python\Python36-32\Scripts\mypackage-script.py", line 11, in <module>
load_entry_point('mypackage==0.1.2', 'console_scripts', 'mypackage')()
File "c:\users\username\appdata\local\programs\python\python36-32\lib\site-packages\pkg_resources\__init__.py", line 572, in load_entry_point
return get_distribution(dist).load_entry_point(group, name)
File "c:\users\username\appdata\local\programs\python\python36-32\lib\site-packages\pkg_resources\__init__.py", line 2755, in load_entry_point
return ep.load()
File "c:\users\username\appdata\local\programs\python\python36-32\lib\site-packages\pkg_resources\__init__.py", line 2408, in load
return self.resolve()
File "c:\users\username\appdata\local\programs\python\python36-32\lib\site-packages\pkg_resources\__init__.py", line 2414, in resolve
module = __import__(self.module_name, fromlist=['__name__'], level=0)
File "c:\users\username\appdata\local\programs\python\python36-32\lib\site-packages\mypackage\__init__.py", line 16, in <module>
import helpers as h
ModuleNotFoundError: No module named 'helpers'
Here is the source tree:
PS C:\Users\username\source\repos\mypackage> tree /F
Folder PATH listing for volume mydisk
Volume serial number is 01234-A321
C:.
│ .gitignore
│ COPYING
│ MANIFEST.in
│ README.rst
│ setup.py
│
├───mypackage
│ │ helpers.py
│ │ __init__.py
│ │
│ └───__pycache__
│ helpers.cpython-36.pyc
│ __init__.cpython-36.pyc
│
└───tests
itsatrap.py
__init__.py
Here is the setup.py:
PS C:\Users\username\source\repos\mypackage> cat setup.py
from setuptools import setup, find_packages
from codecs import open
from os import path
path_to_here = path.abspath(path.dirname(__file__))
with open(path.join(path_to_here, 'README.rst'), encoding='utf-8') as readme_file:
readme = readme_file.read()
with open(path.join(path_to_here, 'COPYING'), encoding='utf-8') as license_file:
license = license_file.read()
setup(
name = 'mypackage',
version = '0.1.2',
license=license,
description = 'Who knows',
long_description = readme,
url = 'https://github.com/user/mypackage',
keywords = ['help!'],
packages = find_packages(exclude=['contrib', 'docs', 'tests']),
install_requires = ['matplotlib','numpy'],
extras_require = {
'dev': [''],
'test': [''],
},
entry_points = {
'console_scripts': [
'mypackage=mypackage:main'
],
},
)
Any help is appreciated. Packaging in Python is new territory for me! This program did run correctly when doing python mypackage/__init__.py from the package's root directory.
In Python 3 all imports are absolute. Use full path to import a module from a package:
from mypackage import helpers as h
To perform relative import do it explicitly:
from . import helpers as h