GAE + Python2.7 + webapp2 + AJAX - ajax

Are there any tutorials or code examples related to AJAX implementation for GAE + Python2.7 + webapp2.
I have tried to follow instructions below:
http://code.google.com/appengine/articles/rpc.html
but I receive the following error:
Traceback (most recent call last):
File "E:\dev\workspace\test\webapp2.py", line 1536, in __call__
rv = self.handle_exception(request, response, e)
File "E:\dev\workspace\test\webapp2.py", line 1530, in __call__
rv = self.router.dispatch(request, response)
File "E:\dev\workspace\test\webapp2.py", line 1278, in default_dispatcher
return route.handler_adapter(request, response)
File "E:\dev\workspace\test\webapp2.py", line 1101, in __call__
handler = self.handler(request, response)
TypeError: __init__() takes exactly 1 argument (3 given)
There is another similar discussion here:
Google App Engine Python Protorpc Error: __call__() takes exactly 1 argument (3 given)
heres is my code from Specialscope's example:
main.py
from BaseHandler import BaseHandler
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers
import logging
from google.appengine.api import files
from google.appengine.api import images
import json
import webapp2
class FileuploadHandler(BaseHandler):
def get(self):
blobstore.create_upload_url('/static')
context={}
self.render_response("uploader.html",**context)
class FileDownloadHandler(blobstore_handlers.BlobstoreUploadHandler,BaseHandler):
def post(self):
upload_files=self.request.POST
#image=upload_files['file']
logging.error(upload_files)
keys=upload_files.keys()
imageurls=[]
for key in keys:
if key.find("uploadimage")!=-1:
image=upload_files[key]
file_name=files.blobstore.create(mime_type='image/jpg')
with files.open(file_name,'a') as f:
f.write(image.value)
files.finalize(file_name)
blob_key=files.blobstore.get_blob_key(file_name)
imageurls.append(images.get_serving_url(blob_key))
context={}
context['imagelinks']=imageurls
self.response.write(json.dumps(context))
app = webapp2.WSGIApplication([
('/upload', FileuploadHandler),
('/download', FileDownloadHandler),
], debug = True)
BaseHandler.py
import webapp2
import os
from webapp2_extras import jinja2
from google.appengine.ext import db
class BaseHandler(webapp2.RequestHandler):
#webapp2.cached_property
def jinja2(self):
# Returns a Jinja2 renderer cached in the app registry.
return jinja2.get_jinja2(app=self.app)
def render_response(self, _template, **context):
# Renders a template and writes the result to the response.
rv = self.jinja2.render_template(_template, **context)
self.response.write(rv)

The stack trace suggests that you have a url mapping in your WSGIApplication that has a group in it, but there's no handler with the corresponding arguments.
If you have
(r'/foo/(\s+)/(\s+)', FooHandler),
then you need
class FooHandler(webapp2.RequestHandler):
def get(self, arg1, arg2):
...
The doc you're using pre-dates Python 2.7 support by several years. Were I in your position, I'd be tempted to get the app working first on Python 2.5, then port to 2.7.

The problem is here:
import webapp2
app = webapp2.WSGIApplication([
('/upload', FileuploadHandler),
('/download', FileDownloadHandler),
], debug = True)
You can't use webapp2.WSGIApplication to construct your application, it doesn't understand protorpc. Instead, do this:
from protorpc.wsgi import service
app = service.service_mappings([
('/upload', FileuploadHandler),
('/download', FileDownloadHandler),
])

Related

Discord Slash Command options not working

I am trying to make a slash command in discord.
import discord
import datetime
import pickle
import os
from discord.ext import commands
from dislash import *
bot = commands.Bot(command_prefix="-")
inter_client = InteractionClient(bot, test_guilds=[345328981039382528])
#bot.event
async def on_ready():
print("Nick ist online!")
#inter_client.slash_command(
name="kick", # Defaults to the function name
description="kick a user",
guild_ids=[345328981039382528],
options=[
create_option(
name="user",
description="Choose a user",
option_type=6,
required=True
)
]
)
async def kick(inter, user:str):
pass
bot.run("-")
If i am trying to run it it says:
Traceback (most recent call last):
line 20, in <module>
create_option(
NameError: name 'create_option' is not defined
So someone said i should add the following line:
from discord_slash.utils.manage_commands import create_option
But this does not help. After adding this it says:
line 7, in <module>
from discord_slash.utils.manage_commands import create_option
ModulNotFoundError: No module named 'discord_slash'
However if i go to cmd and do:
pip install discord-py-slash-command
It says its already installed.
Does anyone know what i am doing wrong? Thanks for helping
options=[
Option("user","Choose a user", OptionType.USER)
]
Try changing your options in the slash command to as follows.

Fiona Driver Error when downloading files via URL

This is simple to test if you get the error on your side:
import geopandas as gpd
gdf = gpd.read_file('https://hepgis.fhwa.dot.gov/fhwagis/AltFuels_Rounds1-5_2021-05-25.zip')
File "fiona/ogrext.pyx", line 540, in fiona.ogrext.Session.start
File "fiona/_shim.pyx", line 90, in fiona._shim.gdal_open_vector
fiona.errors.DriverError: '/vsimem/6101ab5f23764c15b5fe47aa52a049d6' not recognized as a supported file format.
Interestingly, I have received this error for other URLs recently and thought there was something wrong with the URL. But, now I suspect that something else is going on since it is happening with more than one URL. On the other hand, some URLs don't have this issue. One other interesting thing, this error only occurs sometimes. For instance, if I rerun that command it will work maybe 1 out of 20 times.
My Fiona version:
fiona 1.8.20 py39hea8b339_1 conda-forge
Any help would be much appreciated.
Investigating, the URL does not return a zip file. See code below, it actually returns a HTML input page...
import geopandas as gpd
import requests, io
from pathlib import Path
from zipfile import ZipFile, BadZipFile
import urllib
import fiona
url = "https://hepgis.fhwa.dot.gov/fhwagis/AltFuels_Rounds1-5_2021-05-25.zip"
try:
gdf = gpd.read_file(url)
except Exception:
f = Path.cwd().joinpath(urllib.parse.urlparse(url).path.split("/")[-1])
r = requests.get(url, stream=True, headers={"User-Agent": "XY"})
with open(f, "wb") as fd:
for chunk in r.iter_content(chunk_size=128):
fd.write(chunk)
try:
zfile = ZipFile(f)
zfile.extractall(f.stem)
except BadZipFile:
with open(f) as fh:
print(fh.read())

Create class in a different file in MicroPython

I'm trying to use the MPU6050 module for MicroPython in NodeMCU, using uPyCraft as an editor. (https://github.com/larsks/py-mpu6050/blob/master/mpu6050.py)
I've got some troubles and I tried to simplify the code to the point I just try to call a class defined in a different file and I cannot get it to work. This is what I've done so far:
I created a new file (myFile.py) and it looks like:
import machine
class myClass(object):
def __init__(self):
print("init method called")
Then in my main.py I do:
import myFile
myclass = myFile.myClass()
I run main.py and I get this error when doing myclass = myFile.myClass() line:
'module' has no method myClass
I have no experience with MicroPython (although I'm a C# coder) so I'm pretty sure there is some detail about the syntax I'm missing. Any help?
here some tests (file name is the real one, I simplified in the question):
>>> print(open('mpuController.py').read())
import machine
class myClass(object):
def __init__(self):
print("init method called")
other:
>>> print (open('testMPU.py','r').read())
import time
import mpuController
print("starting")
mpu = mpuController.myClass()
print("finished")
and then when running:
exec(open('./testMPU.py').read(),globals())
starting
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 5, in <module>
AttributeError: 'module' object has no attribute 'myClass'
Change
import myFile.py
to
import myFile
You're importing a module (myFile), not a file. Let Python sort it out.

Replace pickle with dill and pymongo call

I finally understood example how to replace pickle with dill from the following discussion: pickle-dill.
For example, the following code worked for me
import os
import dill
import multiprocessing
def run_dill_encoded(what):
fun, args = dill.loads(what)
return fun(*args)
def apply_async(pool, fun, args):
return pool.apply_async(run_dill_encoded, (dill.dumps((fun, args)),))
if __name__ == '__main__':
pool = multiprocessing.Pool(5)
results = [apply_async(pool, lambda x: x*x, args=(x,)) for x in range(1,7)]
output = [p.get() for p in results]
print(output)
I tried to apply the same philosophy to pymongo. The following code
import os
import dill
import multiprocessing
import pymongo
def run_dill_encoded(what):
fun, args = dill.loads(what)
return fun(*args)
def apply_async(pool, fun, args):
return pool.apply_async(run_dill_encoded, (dill.dumps((fun, args)),))
def write_to_db(value_to_insert):
client = pymongo.MongoClient('localhost', 27017)
db = client['somedb']
collection = db['somecollection']
result = collection.insert_one({"filed1": value_to_insert})
client.close()
if __name__ == '__main__':
pool = multiprocessing.Pool(5)
results = [apply_async(pool, write_to_db, args=(x,)) for x in ['one', 'two', 'three']]
output = [p.get() for p in results]
print(output)
produces error:
multiprocessing.pool.RemoteTraceback:
"""
Traceback (most recent call last):
File "C:\Python34\lib\multiprocessing\pool.py", line 119, in worker
result = (True, func(*args, **kwds))
File "C:\...\temp2.py", line 10, in run_dill_encoded
return fun(*args)
File "C:\...\temp2.py", line 21, in write_to_db
client = pymongo.MongoClient('localhost', 27017)
NameError: name 'pymongo' is not defined
"""
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:/.../temp2.py", line 32, in <module>
output = [p.get() for p in results]
File "C:/.../temp2.py", line 32, in <listcomp>
output = [p.get() for p in results]
File "C:\Python34\lib\multiprocessing\pool.py", line 599, in get
raise self._value
NameError: name 'pymongo' is not defined
Process finished with exit code 1
What is wrong?
As I mentioned in the comments, you need to put an import pymongo inside the function write_to_db. This is because when the function is serialized, it does not take along any of the global references with it when it is shipped to the other process space.

Error 1053 When Starting Window Service Written In Python

I have already looked at and tried the resolutions to this question that others have posted. One user said that to try and change my setup.py file from:
from distutils.core import setup
import py2exe
setup(console=["dev.py"])
to
from distutils.core import setup
import py2exe
setup(service=["dev.py"])
I got the following results:
running py2exe
*** searching for required modules ***
Traceback (most recent call last):
File "C:\Python27\Scripts\distutils-setup.py", line 5, in <module>
setup(service=["C:\Python27\Scripts\dev.py"])
File "C:\Python27\lib\distutils\core.py", line 152, in setup
dist.run_commands()
File "C:\Python27\lib\distutils\dist.py", line 953, in run_commands
self.run_command(cmd)
File "C:\Python27\lib\distutils\dist.py", line 972, in run_command
cmd_obj.run()
File "C:\Python27\lib\site-packages\py2exe\build_exe.py", line 243, in run
self._run()
File "C:\Python27\lib\site-packages\py2exe\build_exe.py", line 296, in _run
self.find_needed_modules(mf, required_files, required_modules)
File "C:\Python27\lib\site-packages\py2exe\build_exe.py", line 1274, in
find_needed_modules
mf.import_hook(mod)
File "C:\Python27\lib\site-packages\py2exe\mf.py", line 719, in import_hook
return Base.import_hook(self,name,caller,fromlist,level)
File "C:\Python27\lib\site-packages\py2exe\mf.py", line 136, in import_hook
q, tail = self.find_head_package(parent, name)
File "C:\Python27\lib\site-packages\py2exe\mf.py", line 204, in find_head_package
raise ImportError, "No module named " + qname
ImportError: No module named dev
Now, when I run py2exe with "console" in my setup script it works fine, but the service doesn't start and I get the error. When I run py2exe with "service" in my setup script py2exe doesn't run and tells me it can't find my module.
I have tried to re-install py2exe to no resolution. I have also tried to change:
def SvcDoRun(self):
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_,''))
to
def SvcDoRun(self):
self.ReportServiceStatus(win32service.SERVICE_RUNNING)
win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)
Didn't make a difference either. CAN ANYONE HELP ME PLEASE? Here is what I am working on. It monitors a server and spits back a text file every 60 seconds which I use to monitor my servers at any given minute. Any help you guys and gals can give would be great.
import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
import wmi
import _winreg
from time import sleep
import os
class SrvMonSvc (win32serviceutil.ServiceFramework):
_svc_name_ = "SrvMonSvc"
_svc_display_name_ = "Server Monitor"
def __init__(self,args):
win32serviceutil.ServiceFramework.__init__(self,args)
self.hWaitStop = win32event.CreateEvent(None,0,0,None)
socket.setdefaulttimeout(60)
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_,''))
self.main()
def main(self):
host = wmi.WMI(namespace="root/default").StdRegProv
try:
result, api = host.GetStringValue(
hDefKey = _winreg.HKEY_LOCAL_MACHINE,
sSubKeyName = "SOFTWARE\Server Monitor",
sValueName = "API")
if api == None:
raise Exception
else:
pass
except:
exit()
while 1 == 1:
with open("C:/test.txt", "wb") as b:
computer = wmi.WMI(computer="exsan100")
for disk in computer.Win32_LogicalDisk (DriveType=3):
name = disk.caption
size = round(float(disk.Size)/1073741824, 2)
free = round(float(disk.FreeSpace)/1073741824, 2)
used = round(float(size), 2) - round(float(free), 2)
for mem in computer.Win32_OperatingSystem():
a_mem = (int(mem.FreePhysicalMemory)/1024)
for me in computer.Win32_ComputerSystem():
t_mem = (int(me.TotalPhysicalMemory)/1048576)
u_mem = t_mem - a_mem
for cpu in computer.Win32_Processor():
load = cpu.LoadPercentage
print >>b, api
print >>b, name
print >>b, size
print >>b, used
print >>b, t_mem
print >>b, u_mem
print >>b, load
b.close()
date_list = []
stamp = time.strftime("%c",time.localtime(time.time()))
date_list.append(stamp)
name = re.sub(r"[^\w\s]", "",date_list[0])
os.rename("C:/test.txt", ("C:/%s.txt" % name))
try:
sleep(60.00)
except:
exit()
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(SrvMonSvc)
Have you progressed from your original problem. I had similar problem with a python service and found out that it was missing DLLs since the 'System Path' (not the user path) was not complete.
Running pythonservice.exe with -debug from the command prompt was not a problem because it used correct PATH environment variable, but if your service is installed as a System service it's worth checking out if the System Path variable has all the paths for the required DLLs (MSVC, Python, System32). For me it was missing the python DLLs path, after that it worked again.

Resources