I am trying to get familiar with Flask-APScheduler plug-in through the following sample code: https://github.com/viniciuschiele/flask-apscheduler/blob/master/examples/jobs.py#L1
My project has the following structure:
backend
run.py
application
__init__.py
utilities
__init__.py
views
models
where,
backend>run.py is:
from application import app
app.run(debug=True)
from application import scheduler
scheduler.start()
backend>application>__init__.py is:
from flask import Flask
app = Flask(__name__)
from application.utilities.views import Config
from flask_apscheduler import APScheduler
app.config.from_object(Config())
scheduler = APScheduler()
scheduler.init_app(app)
backend>application>utilities>__init__.py is empty
backend>application>utilities>models.py is empty
backend>application>utilities>views.py is:
class Config(object):
JOBS = [
{
'id': 'job1',
'func': 'application:utilities:views:job1',
'args': (1, 2),
'trigger': {
'type': 'cron',
'second': 10
}
}
]
def job1(a, b):
print(str(a) + ' ' + str(b))
However, I get the following error:
(env)$ python run.py local
Traceback (most recent call last):
File "run.py", line 1, in <module>
from application import app
File "HOME/backend/application/__init__.py", line 106, in <module>
scheduler.init_app(app)
File "/home/xxxxxx/.anaconda/envs/env/lib/python2.7/site-packages/flask_apscheduler/scheduler.py", line 73, in init_app
self.__load_jobs(app)
File "/home/xxxxxx/.anaconda/envs/env/lib/python2.7/site-packages/flask_apscheduler/scheduler.py", line 136, in __load_jobs
self.__load_job(job, app)
File "/home/xxxxxx/.anaconda/envs/env/lib/python2.7/site-packages/flask_apscheduler/scheduler.py", line 159, in __load_job
func = ref_to_obj(func)
File "/home/xxxxxx/.anaconda/envs/env/lib/python2.7/site-packages/apscheduler/util.py", line 264, in ref_to_obj
raise LookupError('Error resolving reference %s: error looking up object' % ref)
LookupError: Error resolving reference application:utilities:views:job1: error looking up object
Does my structure look like ok? Have a placed the right code in the right place? What should I change to make it work?
Your reference should only have one colon (":"). The colon separates the required import from the variable that has to be looked up. So:
'func': 'application.utilities.views:job1'
Related
I need to use aioflask for seting webhooks for my telegram-bot. Here my code, where I set webhook:
from aioflask import Flask, request
...
app = Flask(__name__)
...
#app.route('/')
async def webhook():
await bot.delete_webhook()
await bot.set_webhook(url=APP_URL)
return '!', 200
...
But, when I run app, it give me this error:
Traceback (most recent call last):
File "D:/Python_Projects/FilmMarketBot/check.py", line 1, in <module>
from aioflask import Flask, request
File "D:\Python_Projects\FilmMarketBot\venv\lib\site-packages\aioflask\__init__.py", line 2, in <module>
from .app import Flask
File "D:\Python_Projects\FilmMarketBot\venv\lib\site-packages\aioflask\app.py", line 14, in <module>
from .ctx import AppContext, RequestContext
File "D:\Python_Projects\FilmMarketBot\venv\lib\site-packages\aioflask\ctx.py", line 4, in <module>
from flask.ctx import AppContext as OriginalAppContext, \
ImportError: cannot import name '_app_ctx_stack' from 'flask.ctx' (D:\Python_Projects\FilmMarketBot\venv\lib\site-packages\flask\ctx.py)
Please, tell how can I fix it. ...Why always me?
There seems to be a breaking change in Flask 2.2.0, which causes this incompatibility. As a workaround you can downgrade your Flask package to 2.1.3. This change solved the issue for me.
Reported the issue on GitHub: https://github.com/miguelgrinberg/aioflask/issues/10
(env) C:\Users\recur\Desktop\project\app>python manage.py
Traceback (most recent call last):
File "C:\Users\recur\Desktop\project\app\manage.py", line 1, in <module>
from main import app
File "C:\Users\recur\Desktop\project\app\main\__init__.py", line 47, in <module>
Base.metadata.create_all(bind=engine)
File "C:\Users\recur\Desktop\project\env\lib\site-packages\sqlalchemy\sql\schema.py", line 4888, in create_all
bind = _bind_or_error(self)
File "C:\Users\recur\Desktop\project\env\lib\site-packages\sqlalchemy\sql\base.py", line 1658, in _bind_or_error
raise exc.UnboundExecutionError(msg)
sqlalchemy.exc.UnboundExecutionError: MetaData object is not bound to an Engine or Connection. Execution can not proceed without a database to execute against.
What am I doing wrong?
init.py
from .config import Config
engine = Config.SQLALCHEMY_DATABASE_URI
Base = declarative_base()
Base.query = session.query_property()
Base.metadata.create_all(bind=engine)
config.py
import os
import json
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY')
SQLALCHEMY_DATABASE_URI=os.environ.get('DATABASE_URI')
manage.py
from main import app
if name == 'main':
app.run(host='127.0.0.1', port='5000')
I have a sample BDD scenario in Python Behave. When i run the feature I get the error:
ImportError: No module named features.steps.pages.home_page
I am not sure why it is complaining. home_page.py is in the pages folder, pages is in the steps folder and steps folder is in the features folder.
In pages folder I have an init.py file.
Why is it complaining it cannot find home_page.py?
My code is: features\steps.py
from behave import *
#from features.steps.pages import home_page
from features.steps.pages.home_page import HomePage
#from features.steps.pages import search_page
from features.steps.pages.search_page import SearchPage
from features.steps.pages import home_page
#Given ('we are on the homepage')
def step(context):
context.browser.get('http://www.test.com')
#When ('we enter "{product}" in the search field')
def step(context, product):
#search_field = context.browser.find_element(By.XPATH, 'id("twotabsearchtextbox")')
#search_field.send_keys(product)
home_page = HomePage(context)
home_page.enter_product_in_search_field(product, context)
#When ('And we click the search button')
def step(context):
#search_button = context.browser.find_element(By.XPATH, './/*[#id="nav-search"]/form/div[2]/div/input')
searchPage_results = home_page.click_search_button(context)
#search_button.click()
#Then ('the list of products are displayed')
def step(context):
context.searchPage_results.search_products_results(context)
#wait = WebDriverWait(context.browser, 60)
#divs = wait.until(EC.presence_of_all_elements_located((By.XPATH, '//div/a/h2')))
#for i in divs:
#div2 = divs + '/a/h2'
#print divs.get_attribute('value')
#print divs
#print i.text
#print "i"
# divs
features\steps\pages\home_page.py
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from search_page import SearchPage
class HomePage(object):
def __init__(self, context):
context = context
def enter_product_in_search_field(self, product, context):
search_field = context.browser.find_element(By.XPATH, 'id("twotabsearchtextbox")')
search_field.send_keys(product)
return self
def click_search_button(self, context):
search_button = context.find_element(By.XPATH, './/*[#id="nav-search"]/form/div[2]/div/input').click()
return SearchPage(context)
features\test_feature.feature
Feature: testing product
Scenario Outline: visit test and search for product
Given we are on the test homepage
When we enter "<product>" in the search field
And we click the search button
Then the list of products are displayed
Examples: By product
| Forumla One |
| PS4 |
| Headphones |
My directory structure is:
E:features\test_feature.feature
E:features\init.py
E:features\pages\init.py
E:features\pages\home_page.py
E:features\pages\search_page.py
The full error is:
E:\RL Fusion\projects\BDD\Python BDD\PythonBDD\Selenium Sample\features>behave test_feature.feature
Exception ImportError: No module named features.steps.pages.home_page
Traceback (most recent call last):
File "C:\Python27\lib\runpy.py", line 162, in _run_module_as_main
"__main__", fname, loader, pkg_name)
File "C:\Python27\lib\runpy.py", line 72, in _run_code
exec code in run_globals
File "C:\Python27\scripts\behave.exe\__main__.py", line 9, in <module>
File "C:\Python27\lib\site-packages\behave\__main__.py", line 109, in main
failed = runner.run()
File "C:\Python27\lib\site-packages\behave\runner.py", line 672, in run
return self.run_with_paths()
File "C:\Python27\lib\site-packages\behave\runner.py", line 678, in run_with_paths
self.load_step_definitions()
File "C:\Python27\lib\site-packages\behave\runner.py", line 658, in load_step_definitions
exec_file(os.path.join(path, name), step_module_globals)
File "C:\Python27\lib\site-packages\behave\runner.py", line 304, in exec_file
exec(code, globals, locals)
File "steps\amazon_steps.py", line 6, in <module>
from features.steps.pages.home_page import HomePage
ImportError: No module named features.steps.pages.home_page
How can I resolve this issue?
Thanks, Riaz
It looks like you are not importing your modules correctly. To turn a directory in to a module, change all your init.py files to __init__.py.
Then when you are importing in features/steps.py you can use:
from pages.home_page import HomePage
Same code deployed on development system works fine but once deployed to production fails with following error:
Traceback (most recent call last):
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 240, in Handle
handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler
handler, path, err = LoadObject(self._handler)
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 85, in LoadObject
obj = __import__(path[0])
ImportError: No module named urlhandlers
Following is the URL handler code:
import traceback
import datetime
from google.appengine.api import taskqueue
import re
import webapp2
from utilities.logger import logThis, AEL_LEVEL_INFO, AEL_LEVEL_CRITICAL
from constants.constants import GAET_MASTERTASK_NAME, GAEQ_FOR_MASTERTASK
import sys
class QueueAMasterTask(webapp2.RequestHandler):
def get(self):
try:
dt =datetime.datetime.now()
logThis(AEL_LEVEL_INFO, 'Master Task added to its Q at[%s]' %(dt))
task_name = GAET_MASTERTASK_NAME + str(datetime.datetime.now())
task_name = re.sub('[^a-zA-Z0-9_-]', '_', task_name)
taskqueue.add(queue_name=GAEQ_FOR_MASTERTASK,name=task_name)
logThis(AEL_LEVEL_INFO, "OK-MASTER TASK ADD")
except taskqueue.DuplicateTaskNameError:
logThis(AEL_LEVEL_CRITICAL, "EXCEPTION on QueueAMasterTask-" + traceback.format_exc())
except:
logThis(AEL_LEVEL_CRITICAL, "EXP on QueueAMasterTask-" + traceback.format_exc())
app = webapp2.WSGIApplication([('/QueueAMasterTask', QueueAMasterTask)
], debug=True)
Cron job error log
I come across several problems while trying django unittests library. Something strange happens:
I defined the test like this:
from django.core import management
from django.test import TestCase
from django.test.client import Client
from django.core import mail
from django.test.utils import setup_test_environment
from django.contrib.auth.models import User
from django.db import connection
from goserver.models import ActiveList
class GoserverTestCase(TestCase):
#fixtures = ['dat.json']
def setUp(self):
pass
def test_active_list_works(self):
c = Client()
response = c.post('/')
#print response.status_code
self.assertEquals(True, True)
But after the execution of the code it returns following error:
---------------------------------------------------------------------- Unit Test Code Coverage Results
---------------------------------------------------------------------- Traceback (most recent call last): File "manage.py", line 11, in <module>
execute_manager(settings) File "/opt/local/lib/python2.5/site-packages/Django-1.0.2_final-py2.5.egg/django/core/management/__init__.py", line 340, in execute_manager
utility.execute() File "/opt/local/lib/python2.5/site-packages/Django-1.0.2_final-py2.5.egg/django/core/management/__init__.py", line 295, in execute
self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/local/lib/python2.5/site-packages/Django-1.0.2_final-py2.5.egg/django/core/management/base.py", line 192, in run_from_argv
self.execute(*args, **options.__dict__) File "/opt/local/lib/python2.5/site-packages/Django-1.0.2_final-py2.5.egg/django/core/management/base.py", line 219, in execute
output = self.handle(*args, **options) File "/opt/local/lib/python2.5/site-packages/Django-1.0.2_final-py2.5.egg/django/core/management/commands/test.py", line 33, in handle
failures = test_runner(test_labels, verbosity=verbosity, interactive=interactive) File "/opt/local/lib/python2.5/site-packages/django_test_coverage-0.1-py2.5.egg/django-test-coverage/runner.py", line 58, in run_tests
modules.extend(_package_modules(*pkg)) File "/opt/local/lib/python2.5/site-packages/django_test_coverage-0.1-py2.5.egg/django-test-coverage/runner.py", line 92, in _package_modules
modules.append(__import__(impstr + '.' + name, {}, {}, [''])) File "/Users/oleg/jin/goclub/trunk/jin/goserver/admin.py", line 11, in <module>
admin.site.register(ActiveList, ActiveListAdmin) File "/opt/local/lib/python2.5/site-packages/Django-1.0.2_final-py2.5.egg/django/contrib/admin/sites.py", line 64, in register
raise AlreadyRegistered('The model %s is already registered' % model.__name__) django.contrib.admin.sites.AlreadyRegistered: The model ActiveList is already registered silver:jin oleg$
Admin file looks like this:
from goserver.models import ActiveList, Game
from django.contrib import admin
class ActiveListAdmin(admin.ModelAdmin):
list_display = ('user', "is_Bot", "isActive")
admin.site.register(ActiveList, ActiveListAdmin)
admin.site.register(Game)
I run it all this way:
python manage.py test goserver
Also noticed that if I remove lines
c = Client()
response = c.post('/')
from a test case definition, then no error appears
Looking at the traceback, it looks like you have an app called django_test_coverage-0.1 which is importing your app's admin.py.
It is probably importing it from a different location, such as yourproject.yourapp.admin as opposed to yourapp.admin. Since it's technically seen as a different module, it is re-imported and the admin.site.register calls are made again. This causes the AlreadyRegistered error.
My suggestion would be to remove django_test_coverage app (or fix it).
My questions,
I don't see what is base type/class for TestCase - is it Django Test one, or from Unittest?
it is better to use from Django
How are you runnig test? using Django internal test command, by nose, by unittest? By Traceback I thing test command, but I am not quite sure.
What is you definitions for ActiveAdminList and ActiveList? Have you got maybe class Admin in Meta?
I solve this commenting the admin.autodiscover() line in the proye