getting error when trying start server in pywebio 1.5.2 - python

I get this error:
Traceback (most recent call last):
File "C:\Users\website\Desktop\collector.py", line 10, in <module>
start_server(636)
File "C:\Users\website\AppData\Local\Programs\Python\Python310\lib\site-packages\pywebio\platform\tornado.py", line 360, in start_server
handler = webio_handler(applications, cdn, allowed_origins=allowed_origins, check_origin=check_origin,
File "C:\Users\website\AppData\Local\Programs\Python\Python310\lib\site-packages\pywebio\platform\tornado.py", line 236, in webio_handler
applications = make_applications(applications)
File "C:\Users\website\AppData\Local\Programs\Python\Python310\lib\site-packages\pywebio\platform\page.py", line 171, in make_applications
assert iscoroutinefunction(app) or isgeneratorfunction(app) or callable(app), \
AssertionError: Don't support application type:<class 'int'>
my code:
from time import sleep
from pywebio.input import *
from pywebio.output import *
from pywebio import start_server
import pandas
pandas.options.display.max_rows = 6000
pandas.set_option('display.float_format', lambda x: '%.0f' % x)
a = pandas.read_csv("https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/latest/owid-covid-latest.csv",
delimiter=",",
)
out = (a[["location", "new_cases", "total_cases","new_deaths","total_deaths"]].to_string().replace('\n','\n'+' '*12))
out1 = '{:<11} {}'.format('',out)
Titles1 = out1.replace("location", "Location")
Titles2 = Titles1.replace("new_cases", "New Cases")
Titles3 = Titles2.replace("total_deaths", "Total Deaths")
Titles4 = Titles3.replace("total_cases", "Total Cases")
Titles5 = Titles4.replace("new_deaths", "New deaths")
No0 = Titles5.replace(".0", "")
print(No0)
put_code(No0)
start_server(636)
what I do wrong? Please sorry if somebody asking this question but I can't find answer in Google.
Thanks for suggestions because I'm newbie on this forum :)
Thank you in advance!

Your error comes from this line:
start_server(636)
Note that from the documentation, start_server()'s first argument applications must be a list or a dict or a callable
pywebio.platform.tornado.start_server(applications, port=0, host='', debug=False, cdn=True, static_dir=None, remote_access=False, reconnect_timeout=0, allowed_origins=None, check_origin=None, auto_open_webbrowser=False, max_payload_size='200M', **tornado_app_settings)
applications (list/dict/callable)
PyWebIO application. Can be a task function, a list of functions, or a dictionary. Refer to Advanced topic: Multiple applications in start_server() for more information.
When the task function is a coroutine function, use Coroutine-based session implementation, otherwise, use thread-based session implementation.
The error is telling you that you gave an argument of an unsupported type (int) to the application argument.
AssertionError: Don't support application type:<class 'int'>
If you meant for 636 to be the port on which your server runs, it needs to be the second argument, or passed as a keyword argument.

Related

Trying to make a one hour loop in python

from notifypy import Notify
import schedule
def remember_water():
notification = Notify()
notification.title = "XXX"
notification.message = "XXX"
notification.send()
schedule.every().hour.do(remember_water())
while True:
schedule.run_pending()
time.sleep(1)
Tried to make a notification to drink water every hour... getting a type error when execute, maybe there are some other modules that are better.
Did´nt get in touch with these modules ever, pls help :)
Running your code produces:
Traceback (most recent call last):
File "/home/lars/tmp/python/drink.py", line 11, in <module>
schedule.every().hour.do(remember_water())
File "/home/lars/.local/share/virtualenvs/lars-rUjSNCQn/lib/python3.10/site-packages/schedule/__init__.py", line 625, in do
self.job_func = functools.partial(job_func, *args, **kwargs)
TypeError: the first argument must be callable
Your problem is here:
schedule.every().hour.do(remember_water())
The argument to the .do method must be a callable (like a function), but you are calling your function here and passing the result. You want to pass the function itself:
schedule.every().hour.do(remember_water)

Python RPC Time module function not found

I am trying to get started with Python + gRCP and so I checked out their repository as mentioned in the gRPC guide (https://grpc.io/docs/quickstart/python/).
Now I could execute the Hello World-Script (Client + Server), and so I tried to modify it. To ensure I did not missconfigure anything I just extended the Hello World-function (that use to work out before). I added the following lines:
import time
def SayHello(self, request, context):
currentTime = time.clock_gettime(time.CLOCK_REALTIME)
return helloworld_pb2.HelloReply(message='Time is, %s!' % currentTime)
Now what I inmagined it would do is to simply pass the currentTime-object back in this message I am returning upon that function is called - yet, what happens is the following error:
ERROR:grpc._server:Exception calling application: 'module' object has
no attribute 'clock_gettime' Traceback (most recent call last): File
"/home/user/.local/lib/python2.7/site-packages/grpc/_server.py", line
435, in _call_behavior
response_or_iterator = behavior(argument, context) File "greeter_server.py", line 29, in SayHello
currentTime = time.clock_gettime(time.CLOCK_REALTIME) AttributeError: 'module' object has no attribute 'clock_gettime'
I tried to Google around and I found that this might occur if you have a file named time in the same directory (so Python confuses the file in the current directory with the time-file. Yet there is no such file and he seems to find the correct time-file (since I can see the documentation when I hover the import and the function). What did I do wrong here?
The "full" Server Code (up to the serve() function):
from concurrent import futures
import logging
import time
import grpc
import helloworld_pb2
import helloworld_pb2_grpc
class Greeter(helloworld_pb2_grpc.GreeterServicer):
def SayHello(self, request, context):
currentTime = time.clock_gettime(time.CLOCK_REALTIME)
return helloworld_pb2.HelloReply(message='Time is, %s!' % currentTime)
Edit: I am using Ubuntu if that is important.
time.clock_gettime is a 3.3+ API and you are using 2.7.

Telegram TypeError: the first argument must be callable

I'm trying to do post automatic schedule in Telegram. It runs first run but after its try to looping I get an error:
TypeError: the first argument must be callable
My code :
import time
import schedule
from pyrogram import Client, ReplyKeyboardMarkup, InlineKeyboardMarkup, InlineKeyboardButton
from pyrogram.api import functions, types
from pyrogram.api.errors import FloodWait
person1 = Client(
session_name="*cenzored*",
api_id=*cenzored*,
api_hash="*cenzored*"
)
person2 = Client(
session_name="*cenzored*",
api_id=*cenzored*,
api_hash="*cenzored*"
)
wick.start()
def Publish(session,dat,msgid,session_name):
try:
session.start()
print("[%s]Posting..." % (session_name))
session.send(
functions.messages.GetBotCallbackAnswer(
peer=session.resolve_peer("*cenzored*"),
msg_id=msgid,
data=b'publish %d' % (dat)
)
)
session.idle()
except:
print("Crashed,starting over")
schedule.every(0.3).minutes.do(Publish(person1,142129,12758, 'Dani')) // Here is the line is crashing.
schedule.every(0.3).minutes.do(Publish(person2,137351,13177, 'Wick'))
while 1:
schedule.run_pending()
time.sleep(1)
Traceback :
Pyrogram v0.7.4, Copyright (C) 2017-2018 Dan Tès <https://github.com/delivrance>
Licensed under the terms of the GNU Lesser General Public License v3 or later (LGPLv3+)
[person1]Posting...
3: 2018-06-16 12:07:26.529829 Retrying <class 'pyrogram.api.functions.messages.get_bot_callback_answer.GetBotCallbackAnswer'>
4: 2018-06-16 12:07:42.041309 Retrying <class 'pyrogram.api.functions.messages.get_bot_callback_answer.GetBotCallbackAnswer'>
Crashed,starting over
Traceback (most recent call last):
File "C:\Users\343df\OneDrive\Desktop\Maor\python\tele\tele.py", line 35, in <module>
schedule.every(0.3).minutes.do(Publish('ss',dani,140129,12758, 'Dani'))
File "C:\Program Files (x86)\Python36-32\lib\site-packages\schedule\__init__.py", line 385, in do
self.job_func = functools.partial(job_func, *args, **kwargs)
TypeError: the first argument must be callable
Basically my problem is that is not running (TypeError: the first argument must be callable) after first time and its scheduled to run every 0.3 seconds.
According to [ReadTheDocs]: do(job_func, *args, **kwargs), you don't have to call Publish, but just pass it, followed by its argument list (the call will be performed by schedule framework):
schedule.every(0.3).minutes.do(Publish, person1, 142129, 12758, "Dani")
schedule.every(0.3).minutes.do(Publish, person2, 137351, 13177, "Wick")
.do() expects a callable as the first argument (and additional arguments to .do will be passed to that callable).
So instead of:
schedule.every(0.3).minutes.do(Publish(person1,142129,12758, 'Dani'))
schedule.every(0.3).minutes.do(Publish(person2,137351,13177, 'Wick'))
you likely want:
schedule.every(0.3).minutes.do(Publish, person1, 142129, 12758, 'Dani')
schedule.every(0.3).minutes.do(Publish, person2, 137351, 13177, 'Wick')

Python can't import WMI under special circumstance

I've created a standalone exe Windows service written in Python and built with pyInstaller. When I try to import wmi, an exception is thrown.
What's really baffling is that I can do it without a problem if running the code in a foreground exe, or a foreground python script, or a python script running as a background service via pythonservice.exe!
Why does it fail under this special circumstance of running as a service exe?
import wmi
Produces this error for me:
com_error: (-2147221020, 'Invalid syntax', None, None)
Here's the traceback:
Traceback (most recent call last):
File "<string>", line 43, in onRequest
File "C:\XXX\XXX\XXX.pyz", line 98, in XXX
File "C:\XXX\XXX\XXX.pyz", line 31, in XXX
File "C:\XXX\XXX\XXX.pyz", line 24, in XXX
File "C:\XXX\XXX\XXX.pyz", line 34, in XXX
File "C:\Program Files (x86)\PyInstaller-2.1\PyInstaller\loader\pyi_importers.py", line 270, in load_module
File "C:\XXX\XXX\out00-PYZ.pyz\wmi", line 157, in <module>
File "C:\XXX\XXX\out00-PYZ.pyz\win32com.client", line 72, in GetObject
File "C:\XXX\XXX\out00-PYZ.pyz\win32com.client", line 87, in Moniker
wmi.py line 157 has a global call to GetObject:
obj = GetObject ("winmgmts:")
win32com\client__init.py__ contains GetObject(), which ends up calling Moniker():
def GetObject(Pathname = None, Class = None, clsctx = None):
"""
Mimic VB's GetObject() function.
ob = GetObject(Class = "ProgID") or GetObject(Class = clsid) will
connect to an already running instance of the COM object.
ob = GetObject(r"c:\blah\blah\foo.xls") (aka the COM moniker syntax)
will return a ready to use Python wrapping of the required COM object.
Note: You must specifiy one or the other of these arguments. I know
this isn't pretty, but it is what VB does. Blech. If you don't
I'll throw ValueError at you. :)
This will most likely throw pythoncom.com_error if anything fails.
"""
if clsctx is None:
clsctx = pythoncom.CLSCTX_ALL
if (Pathname is None and Class is None) or \
(Pathname is not None and Class is not None):
raise ValueError("You must specify a value for Pathname or Class, but not both.")
if Class is not None:
return GetActiveObject(Class, clsctx)
else:
return Moniker(Pathname, clsctx)
The first line in Moniker(), i.e. MkParseDisplayName() is where the exception is encountered:
def Moniker(Pathname, clsctx = pythoncom.CLSCTX_ALL):
"""
Python friendly version of GetObject's moniker functionality.
"""
moniker, i, bindCtx = pythoncom.MkParseDisplayName(Pathname)
dispatch = moniker.BindToObject(bindCtx, None, pythoncom.IID_IDispatch)
return __WrapDispatch(dispatch, Pathname, clsctx=clsctx)
Note: I tried using
pythoncom.CoInitialize()
which apparently solves this import problem within a thread, but that didn't work...
I also face the same issue and I figure out this issue finally,
import pythoncom and CoInitialize pythoncom.CoInitialize (). They import wmi
import pythoncom
pythoncom.CoInitialize ()
import wmi
I tried solving this countless ways. In the end, I threw in the towel and had to just find a different means of achieving the same goals I had with wmi.
Apparently that invalid syntax error is thrown when trying to create an object with an invalid "moniker name", which can simply mean the service, application, etc. doesn't exist on the system. Under this circumstance "winmgmts" just can't be found at all it seems! And yes, I tried numerous variations on that moniker with additional specs, and I tried running the service under a different user account, etc.
Honestly I didn't dig in order to understand why this occurs.
Anyway, the below imports solved my problem - which was occurring only when ran from a Flask instance:
import os
import pythoncom
pythoncom.CoInitialize()
from win32com.client import GetObject
import wmi
The error "com_error: (-2147221020, 'Invalid syntax', None, None)" is exactly what popped up in my case so I came here after a long time of searching the web and voila:
Under this circumstance "winmgmts" just can't be found at all it
seems!
This was the correct hint for because i had just a typo , used "winmgmt:" without trailing 's'. So invalid sythax refers to the first methods parameter, not the python code itself. o_0 Unfortunately I can't find any reference which objects we can get with win32com.client.GetObject()... So if anybody has a hint to which params are "allowed" / should work, please port it here. :-)
kind regards
ChrisPHL

TypeError: unhashable type: 'dict' for python

I'm trying to setup a cron auto delete file on Deluge torrent client, code is as following:
import sys
import os
import subprocess
import logging
from datetime import datetime, date, time, timedelta
from deluge.ui.client import client
import deluge.component as component
from deluge.log import LOG as log
from twisted.internet import reactor
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
def printData(dresult):
if dresult:
print "Command executed with result: ", dresult
else:
sys.stderr.write(str(failure))
def on_connect_success(result):
def on_get_torrent_value(value):
for torrent in value:
seedtime = datetime.fromtimestamp(value[torrent]["seeding_time"]) - datetime.fromtimestamp(0)
if value[torrent]["label"] in labels and value[torrent]["is_finished"] == True and seedtime >= timedelta(hours = totalseedtime):
--- multiple of commands ---
client.disconnect()
reactor.stop()
client.core.get_torrents_status({}, ["name", "is_finished", "save_path", "seeding_time", "label"]).addCallback(on_get_torrent_value)
client.core.remove_torrent({}, remove_data = False).addCallbacks(printData)
d.addCallback(on_connect_success)
def on_connect_fail(result):
print "result:", result
d.addErrback(on_connect_fail)
reactor.run()
When executed, the debug log returned:
DEBUG:deluge:ConfigManager started..
INFO:deluge:Connecting to daemon at 127.0.0.1:58846..
INFO:deluge:Connected to daemon at 127.0.0.1:58846..
ERROR:deluge:RPCError Message Received!
--------------------------------------------------------------------------------
RPCRequest: core.remove_torrent({}, remove_data=False)
--------------------------------------------------------------------------------
File "/usr/local/lib/python2.7/dist-packages/deluge-1.3.11-py2.7.egg/deluge/core/rpcserver.py", line 299, in dispatch
ret = self.factory.methods[method](*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/deluge-1.3.11-py2.7.egg/deluge/core/core.py", line 326, in remove_torrent
return self.torrentmanager.remove(torrent_id, remove_data)
File "/usr/local/lib/python2.7/dist-packages/deluge-1.3.11-py2.7.egg/deluge/core/torrentmanager.py", line 568, in remove
torrent_name = self.torrents[torrent_id].get_status(["name"])["name"]
TypeError: unhashable type: 'dict'
--------------------------------------------------------------------------------
Unhandled error in Deferred:
Unhandled Error
Traceback (most recent call last):
Failure: deluge.ui.client.DelugeRPCError: <deluge.ui.client.DelugeRPCError object at 0x1aeae50>
INFO:deluge:Connection lost to daemon at 127.0.0.1:58846 reason: Connection to the other side was lost in a non-clean fashion: Connection lost.
I understand that the dic I pass to client.core.remove_torrent is something wrong in format, but dont know how to fix it. Any help in much appreciate! Thanks so much in advance.
You can't use a dict as a key (it's mutable - see the description of frozenset for an explanation).
It looks like you're supposed to pass some torrent_id to remove, and whatever this is, it must be something hashable - ie, not a dict.

Categories

Resources