Falcon (Waitress) tutorial module object is not callable - windows

So I am going through Falcon tutorial on windows 10 with venv
falcon==1.4.1
waitress==1.1.0
User guide went well but it was served with:
httpd = simple_server.make_server('127.0.0.1', 8000, app)
httpd.serve_forever()
The tutorial works with two files for now:
resource.py:
import json
import falcon
class Resource(object):
def on_get(self, req, resp):
doc = {
'images': [
{
'href': '/images/1eaf6ef1-7f2d-4ecc-a8d5-6e8adba7cc0e.png'
}
]
}
resp.body = json.dumps(doc, ensure_ascii=False)
resp.status = falcon.HTTP_200
app.py:
import falcon
from .images import Resource
api = application = falcon.API()
images = Resource()
api.add_route('/images', images)
waitress initiated with:
waitress-serve --port=8000 look:app
request made with:
http localhost:8000/images
error response:
ERROR:waitress:Exception when serving /images Traceback (most recent
call last): File
"c:\users\ivan\dev\py\projects\falcon\look.venv\lib\site-packages\waitress\channel.py",
line 338, in service
task.service() File "c:\users\ivan\dev\py\projects\falcon\look.venv\lib\site-packages\waitress\task.py",
line 169, in service
self.execute() File "c:\users\ivan\dev\py\projects\falcon\look.venv\lib\site-packages\waitress\task.py",
line 399, in execute
app_iter = self.channel.server.application(env, start_response) TypeError: 'module' object is not callable
Any ideas / inputs how to overcome this ?

Found an issue, the tutorial in falcon framework got it wrong with the waitress command.
Here is the related github issue.
The command should be:
waitress-serve --port=8000 look.app:api

Related

Unable to access file (url_private property) when file was uploaded by slackbot

I'm trying to upload a file using slackbot and then posting it as a url_private link in my channel. Then when I click on the url_private link the browser throws the error:
The page isn’t redirecting properly An error occurred during a connection to xxx.slack.com. This problem can sometimes be caused by disabling or refusing to accept cookies.
My code:
client = WebClient(token=os.environ.get("SLACK_BOT_TOKEN"))
logger = logging.getLogger(__name__)
try:
result = client.files_upload(
initial_comment="Here's my file :smile:",
file=file_name,
)
logger.info(result)
os.environ['PRIVATE_URL'] = result["file"]["url_private"]
except SlackApiError as e:
logger.error("Error uploading file: {}".format(e))
def post_message_to_slack(blocks = None):
return requests.post('https://slack.com/api/chat.postMessage', {
'token': os.environ['USER_TOKEN'],
'channel': "#test",
'as_user': 'username',
'blocks': json.dumps(blocks)
}).json()
print(post_message_to_slack(blocks))
This is how I receive result:
The SLACK_BOT_TOKEN and USER_TOKEN has files:write, files:read permissions.
I don't know why I'm not able to access the file after I login to my slack account.

Fresh prestashop 1.7 install curl timeout

I am trying to install Prestashop on my local machine
Using ubuntu 18.04, php 7.2, mysql 5.6, apache 2.4
I have cloned from their github repo, checkouted to branch 1.7.6.x, installed composer dependencies and made a symbolic link to the code directory from my /var/www/html (didn't want to bother creating a vhost)
Opened chromium to http://127.0.0.1/prestashop/install-dev/index.php
Proceeded with all steps, with correct mysql settings, directory permission settings, left the language to English (English)
But during the Store Installation step, when "Installing addons modules", it fails with a curl error like this:
file_get_contents_curl failed to download http://i18n.prestashop.com/translations/1.7.6.7/en-US/en-US.zip : (error code 28) Operation timed out after 5001 milliseconds with 221832 out of 516048 bytes received
I also have the following info in the Request tab of my inspector:
It's calling http://127.0.0.1/prestashop/install-dev/index.php?installModulesAddons=true&_=1596718771175 with status_code 200
I have the following as response body in there:
{
"success":false,
"message":"file_get_contents_curl failed to download http:\/\/i18n.prestashop.com\/translations\/1.7.6.7\/en-US\/en-US.zip : (error code 28) Operation timed out after 5001 milliseconds with 221832 out of 516048 bytes received"
}
I checked the file in install-dev/controllers/http/process.php but the code that I think is called just looks like this:
/**
* PROCESS : installModulesAddons
* Install modules from addons
*/
public function processInstallAddonsModules()
{
$this->initializeContext();
if (($module = Tools::getValue('module')) && $id_module = Tools::getValue('id_module')) {
$result = $this->model_install->installModulesAddons(array('name' => $module, 'id_module' => $id_module));
} else {
$result = $this->model_install->installModulesAddons();
}
if (!$result || $this->model_install->getErrors()) {
$this->ajaxJsonAnswer(false, $this->model_install->getErrors());
}
$this->session->process_validated = array_merge($this->session->process_validated, array('installModulesAddons' => true));
$this->ajaxJsonAnswer(true);
}
I suspect my faulty internet is to blame, but is there a workaround to increase the curl timeout?
Comment the code lines like this:

How to create and execute a function using the Apps Script API

I created a script following "Ruby Quickstart" but I can't run it with the API.
I know that I should publish it as API executable. To do that I need to switch the script project to use a "standard GCP project" and I couldn't find how to do it from the API.
If I switch it manually it works. When I execute the code below I get this error:
> 403, PERMISSION_DENIED: The caller does not have permission
This is the code:
def create_and_execute
# Initialize the API
service = Google::Apis::ScriptV1::ScriptService.new
service.client_options.application_name = APPLICATION_NAME
service.authorization = authorize
# Make the API request.
request = Google::Apis::ScriptV1::CreateProjectRequest.new(
title: "My Script3"
)
resp = service.create_project request
script_id = resp.script_id
content = Google::Apis::ScriptV1::Content.new(
files: [
Google::Apis::ScriptV1::File.new(
name: "hello",
type: "SERVER_JS",
source: "function helloWorld() {\n console.log('Hello, world!');\n}"
),
Google::Apis::ScriptV1::File.new(
name: "appsscript",
type: "JSON",
source: "{\"timeZone\":\"America/Los_Angeles\",\"exceptionLogging\":\"CLOUD\",\"executionApi\":{\"access\":\"ANYONE\"}}"
)
],
script_id: script_id
)
service.update_project_content(script_id, content)
service.create_project_version(script_id,Google::Apis::ScriptV1::Version.new(script_id: script_id))
service.create_project_deployment(script_id,Google::Apis::ScriptV1::DeploymentConfig.new(script_id: script_id,version_number: 1))
service.run_script(script_id, Google::Apis::ScriptV1::ExecutionRequest.new(function: 'helloWorld', dev_mode: true))
end
I am sorry to inform you that this operation is not possible. You need to use a standard browser interface (read as not an API) to switch a GCP project as described here. On this docs you can find more information about how to use Apps Script on your app, and here you can learn how to activate any API (included Apps Scripts API).

ModuleNotFound : Heroku log showing error on Procfile and fails to launch flask app

I am working on a simple flask Todo list web app with postgres database and I tried deploying it to heroku but it is giving me an error saying
Application error
An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details.
I followed the Quickstart correctly but that did not help
when I check logs by heroku logs --tail It says
ModuleNotFoundError:No module named TodoApp
There are no error logs on command promt also. I can not find any way to check what is going wrong.
This is in my Procfile
web: gunicorn TodoApp:app
This is in my requirements.txt
asn1crypto==0.22.0
certifi==2017.4.17
cffi==1.10.0
chardet==3.0.4
click==6.7
cryptography==1.9
enum34==1.1.6
Flask==0.12.2
Flask-SQLAlchemy==2.2
Flask-WTF==0.14.2
gunicorn==19.7.1
idna==2.5
ipaddress==1.0.18
itsdangerous==0.24
Jinja2==2.9.6
MarkupSafe==1.0
psycopg2==2.7.1
pycparser==2.17
PyJWT==1.5.0
pyOpenSSL==17.0.0
pytz==2017.2
requests==2.18.1
six==1.10.0
SQLAlchemy==1.1.10
twilio==6.4.1
urllib3==1.21.1
Werkzeug==0.12.2
WTForms==2.1
This is my todo.py file
from flask import Flask, render_template , Response
from flask import request , jsonify
from models import db ,db1, User
from flask_sqlalchemy import SQLAlchemy
from message import client
import json
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] =
'postgresql://postgres:Abcd#123456#localhost/learningflask'
db.init_app(app)
#app.route("/")
def index():
return render_template("index.html",User=User.query.all())
#app.route("/getdata", methods=['GET'])
def get_User():
myuser=User.query.all()
if myuser =="":
return 404
return Response(json.dumps({'taskname':[user.taskname for user in
myuser]}), mimetype='application/json')
#app.route('/', methods=['POST'])
def my_form_post():
text=request.form['text']
if text !="":
newuser = User(text)
db.session.add(newuser)
db.session.commit()
message = client.messages.create(
to="", from_="" , body ="A task has
been added to your todo list : "+ text)
print(message.sid)
return render_template("index.html",User=User.query.all())
else:
newuser = request.form.getlist('removeId')
if newuser:
for n in newuser:
User.query.filter_by(uid=n).delete()
db.session.commit()
return render_template("index.html",User=User.query.all())
else:
edituser = request.form.getlist('editId')
if edituser:
updatedText=request.form['updatedText']
for e in edituser:
User.query.filter_by(uid=e).update(dict(taskname=updatedText))
db.session.commit()
return
render_template("index.html",User=User.query.all())
if __name__ == "__main__":
app.run(debug=True)
db.create_all()
Here is the folder structure
The error might be in this line:
web: gunicorn TodoApp:app
you should use the file name before the : and then the flask object you have created.
web: gunicorn Todo:app
this should work. toto:app is the <filename>:<appname> .

No handlers could be found for logger "django_facebook.models"

while installing django_facebook, i got an error :
Validating models...
No handlers could be found for logger "django_facebook.models"
Unhandled exception in thread started by <function wrapper at 0x1032a5758>
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/django/utils/autoreload.py", line 93, in wrapper
fn(*args, **kwargs)
File "/Library/Python/2.7/site-packages/django/core/management/commands/runserver.py", line 101, in inner_run
self.validate(display_num_errors=True)
File "/Library/Python/2.7/site-packages/django/core/management/base.py", line 310, in validate
num_errors = get_validation_errors(s, app)
File "/Library/Python/2.7/site-packages/django/core/management/validation.py", line 113, in get_validation_errors
from django.utils.image import Image
File "/Library/Python/2.7/site-packages/django/utils/image.py", line 154, in <module>
Image, _imaging, ImageFile = _detect_image_library()
File "/Library/Python/2.7/site-packages/django/utils/image.py", line 108, in _detect_image_library
_("Neither Pillow nor PIL could be imported: %s") % err
django.core.exceptions.ImproperlyConfigured: Neither Pillow nor PIL could be imported: No module named Image
It is a pure django project created by pycharm. I was following the document of django_facebook, installation section. What I do is just get facebook app and type the code 'django_facebook' in INSTALLED_APP in settings.py.
It's same results when syncdb also.
I'm using python-2.7.5 and django-1.6.5.
I can't find any answer to solve this. anybody knows this?
Regarding the warningNo handlers could be found for logger "django_facebook.models" and not the error. This question came up on search for that warning, thought this would be useful for others.
django-facebook outputs logs when in operation, just like other django components do. You have to tell Django what you want to do with these messages. In django terminology the app outputs some messages as a logger without needing to know what to do with them, you have to then patch these to a handler which doesn't know anything about your use case, but does know about sending emails/texts/carrier pigeons.
In your settings.py file find LOGGING=..., in the loggers dict you will have to specify what handlers you want to handle the output from django-facebook.
For more information see the docs on logging https://djangoproject.com/en/dev/topics/logging/
My logging variable looks like this, notice the bit at the bottom:
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
},
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
},
},
'loggers': {
'django.request': {
'handlers': ['mail_admins','console'],
'level': 'ERROR',
'propagate': True,
},
'django_facebook.models': {
'handlers': ['mail_admins','console'],
'level': 'ERROR',
'propagate': True,
}
}
}
You could try pip install pillow

Resources