I tried to test some Solidity contracs with Pyton Webserver 3 to interact by web-UI with Metamask. Pyton is working fine, but I only get the project directory not the desired webUI with a button and Pyton sends
::ffff:127.0.0.1 - - [14/Feb/2023 16:18:25] "GET / HTTP/1.1" 200 -
::ffff:127.0.0.1 - - [15/Feb/2023 10:13:58] "GET /src/ HTTP/1.1" 200 -
::ffff:127.0.0.1 - - [15/Feb/2023 10:14:04] code 404, message File not found
::ffff:127.0.0.1 - - [15/Feb/2023 10:14:04] "GET /favicon.ico HTTP/1.1" 404 -
----------------------------------------
Exception occurred during processing of request from ('::ffff:127.0.0.1', 62286, 0, 0)
Traceback (most recent call last):
File "C:\Users\GCC-V\AppData\Local\Programs\Python\Python311\Lib\http\server.py", line 726, in send_head
f = open(path, 'rb')
^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\_jpegdegens\\favicon.ico'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\GCC-V\AppData\Local\Programs\Python\Python311\Lib\socketserver.py", line 691, in process_request_thread
self.finish_request(request, client_address)
File "C:\Users\GCC-V\AppData\Local\Programs\Python\Python311\Lib\http\server.py", line 1306, in finish_request
self.RequestHandlerClass(request, client_address, self,
File "C:\Users\GCC-V\AppData\Local\Programs\Python\Python311\Lib\http\server.py", line 667, in __init__
super().__init__(*args, **kwargs)
File "C:\Users\GCC-V\AppData\Local\Programs\Python\Python311\Lib\socketserver.py", line 755, in __init__
self.handle()
File "C:\Users\GCC-V\AppData\Local\Programs\Python\Python311\Lib\http\server.py", line 432, in handle
self.handle_one_request()
File "C:\Users\GCC-V\AppData\Local\Programs\Python\Python311\Lib\http\server.py", line 420, in handle_one_request
method()
File "C:\Users\GCC-V\AppData\Local\Programs\Python\Python311\Lib\http\server.py", line 671, in do_GET
f = self.send_head()
^^^^^^^^^^^^^^^^
File "C:\Users\GCC-V\AppData\Local\Programs\Python\Python311\Lib\http\server.py", line 728, in send_head
self.send_error(HTTPStatus.NOT_FOUND, "File not found")
File "C:\Users\GCC-V\AppData\Local\Programs\Python\Python311\Lib\http\server.py", line 487, in send_error
self.wfile.write(body)
File "C:\Users\GCC-V\AppData\Local\Programs\Python\Python311\Lib\socketserver.py", line 834, in write
self._sock.sendall(b)
ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine
----------------------------------------
I'm not sure, if that's a problem with Pyton itself or if something's missing in index.ts
import { ethers } from "ethers";
function getEth()
{
// #ts-ignore
const eth = window.etherium;
if (!eth)
{
throw new Error("please get Metamask");
}
return eth;
}
async function hasAccounts()
{
const eth = getEth();
const accounts = await eth.request({method: "eth_accounts"}) as string[];
return accounts && accounts.length;
}
async function requestAccounts()
{
const eth = getEth();
const accounts = await eth.request({method: "eth_requestAccounts"}) as string[];
return accounts && accounts.length;
}
async function run()
{
if (!await hasAccounts() && !await requestAccounts())
{
throw new Error("Please let me take your money");
}
const counter = new ethers.Contract
(
process.env.CONTRACT_ADDRESS,
[
"function count() public",
"function function getCounter() public view returns(uint)",
],
new ethers.providers.Web3Provider(getEth()).getSigner()
)
const el = document.createElement("div");
async function setCounter()
{
el.innerHTML = await counter.getCounter();
}
setCounter();
const button = document.createElement("button");
button.innerText = "increment";
button.onclick = async function()
{
await counter.count();
//setCounter();
}
document.body.appendChild(el);
document.body.appendChild(button);
}
run();
index.html and index.ts are in the same directory named /src and if I go into that directory in the localhost-Window it only shows an empty screen, Source code
<html>
<head>
<body></body>
</head>
</html>
Is there a better webserver than Pyton to test contracts on localshost?
starting Python and calling/ refresing localhost:8000
Your web server expects a favicon
Errno 2] No such file or directory: 'C:\\_jpegdegens\\favicon.ico
I would assume adding this file will make your web server to function properly.
Wikipedia has more information what is a favicon and how to create one.
Related
I have an old bot that I'm trying to transfer to discord.py v2. Asyncpg isn't working and I'm not sure why. I've tried putting the loop and pool in the on_ready and setup_hook but that didn't work either.
import discord
from discord import app_commands
import aiohttp
import asyncio
import requests
from discord.ext import commands
import os
import asyncpg
# Pydest
# Define Client
class Aclient(commands.Bot):
def __init__(self):
super().__init__(command_prefix='.', intents=discord.Intents.default())
self.synced = False
async def setup_hook(self):
cog = await self.load_extension('cogs.weather')
print(f"Loaded All Cogs")
if not self.synced:
await self.tree.sync()
self.synced = True
async def on_ready(self):
await self.wait_until_ready()
if not self.synced:
await self.tree.sync()
self.synced = True
await client.change_presence(status=discord.Status.dnd)
print(f'We have logged in as {self.user}')
client=Aclient()
# test command
#client.tree.command(name="test", description="testing")
async def test(interaction: discord.Interaction, name: str):
async with pool.acquire() as connection:
async with connection.transaction():
check = await connection.fetchrow('select * from weather')
print(check)
await connection.close()
loop = asyncio.get_event_loop()
pool = loop.run_until_complete(asyncpg.create_pool(**credentials))
I'm getting this error:
Traceback (most recent call last):
File "/Users/prathik/Documents/GitHub/red/YELLOW/bot.py", line 61, in test
async with connection.transaction():
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/asyncpg/transaction.py", line 62, in __aenter__
await self.start()
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/asyncpg/transaction.py", line 138, in start
await self._connection.execute(query)
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/asyncpg/connection.py", line 317, in execute
return await self._protocol.query(query, timeout)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "asyncpg/protocol/protocol.pyx", line 338, in query
RuntimeError: Task <Task pending name='CommandTree-invoker' coro=<CommandTree._from_interaction.<locals>.wrapper() running at /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/app_commands/tree.py:1089>> got Future <Future pending cb=[Protocol._on_waiter_completed()]> attached to a different loop
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/app_commands/commands.py", line 851, in _do_call
return await self._callback(interaction, **params) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/prathik/Documents/GitHub/red/YELLOW/bot.py", line 60, in test
async with pool.acquire() as connection:
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/asyncpg/pool.py", line 220, in release
raise ex
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/asyncpg/pool.py", line 210, in release
await self._con.reset(timeout=budget)
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/asyncpg/connection.py", line 1366, in reset
await self.execute(reset_query, timeout=timeout)
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/asyncpg/connection.py", line 317, in execute
return await self._protocol.query(query, timeout)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "asyncpg/protocol/protocol.pyx", line 323, in query
File "asyncpg/protocol/protocol.pyx", line 707, in asyncpg.protocol.protocol.BaseProtocol._check_state
asyncpg.exceptions._base.InterfaceError: cannot perform operation: another operation is in progress
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/app_commands/tree.py", line 1240, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/app_commands/commands.py", line 876, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/app_commands/commands.py", line 869, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'test' raised an exception: InterfaceError: cannot perform operation: another operation is in progress
Does anyone know why this is happening?
I am trying to enable all requests to be logged (to centralized logging system) in a Quart microservice. However this only occurs when running directly in Python, and when running in Hypercorn it only logs major events and errors.
Running from PyCharm does generate the logs (to console, and to centralized log):
# TryLogging.py
import logging
from quart import Quart
app = Quart(__name__)
app.logger.setLevel(logging.INFO)
#app.route("/")
def callme():
return "I'm alive!"
#app.route("/fake_fail")
def failme():
raise Exception("Fake exception")
if __name__ == "__main__":
app.run()
generates console logs:
* Serving Quart app 'TryLogging'
* Environment: production
* Please use an ASGI server (e.g. Hypercorn) directly in production
* Debug mode: False
* Running on http://127.0.0.1:5000 (CTRL + C to quit)
[2022-01-10 15:55:48,323] Running on http://127.0.0.1:5000 (CTRL + C to quit)
[2022-01-10 15:55:50,080] 127.0.0.1:63560 GET / 1.1 200 10 4515
[2022-01-10 15:55:54,480] 127.0.0.1:63560 GET /fake_fail 1.1 500 290 1999
[2022-01-10 15:55:54,478] ERROR in app: Exception on request GET /fake_fail
Traceback (most recent call last):
File "C:\Users\brend\miniconda3\envs\ms-abs-boundaries\lib\site-packages\quart\app.py", line 1489, in handle_request
return await self.full_dispatch_request(request_context)
File "C:\Users\brend\miniconda3\envs\ms-abs-boundaries\lib\site-packages\quart\app.py", line 1514, in full_dispatch_request
result = await self.handle_user_exception(error)
File "C:\Users\brend\miniconda3\envs\ms-abs-boundaries\lib\site-packages\quart\app.py", line 964, in handle_user_exception
raise error
File "C:\Users\brend\miniconda3\envs\ms-abs-boundaries\lib\site-packages\quart\app.py", line 1512, in full_dispatch_request
result = await self.dispatch_request(request_context)
File "C:\Users\brend\miniconda3\envs\ms-abs-boundaries\lib\site-packages\quart\app.py", line 1557, in dispatch_request
return await self.ensure_async(handler)(**request_.view_args)
File "C:\Users\brend\miniconda3\envs\ms-abs-boundaries\lib\site-packages\quart\utils.py", line 66, in _wrapper
result = await loop.run_in_executor(
File "C:\Users\brend\miniconda3\envs\ms-abs-boundaries\lib\concurrent\futures\thread.py", line 58, in run
result = self.fn(*self.args, **self.kwargs)
File "C:\Users\brend\Documents\GitHub\ms-abs-boundaries\src\TryLogging.py", line 15, in failme
raise Exception("Fake exception")
Exception: Fake exception
However when running through Hypercorn in terminal (as it launched in production) and calling the endpoint from browser:
(ms-abs-boundaries) PS C:\Users\brend\Documents\GitHub\ms-abs-boundaries\src> hypercorn --bind 127.0.0.1:5008 TryLoggi
ng.py
[2022-01-10 15:56:42 +1100] [37772] [INFO] Running on http://127.0.0.1:5008 (CTRL + C to quit)
[2022-01-10 15:56:48,075] ERROR in app: Exception on request GET /fake_fail
Traceback (most recent call last):
File "C:\Users\brend\miniconda3\envs\ms-abs-boundaries\lib\site-packages\quart\app.py", line 1489, in handle_request
return await self.full_dispatch_request(request_context)
File "C:\Users\brend\miniconda3\envs\ms-abs-boundaries\lib\site-packages\quart\app.py", line 1514, in full_dispatch_
request
result = await self.handle_user_exception(error)
File "C:\Users\brend\miniconda3\envs\ms-abs-boundaries\lib\site-packages\quart\app.py", line 964, in handle_user_exc
eption
raise error
File "C:\Users\brend\miniconda3\envs\ms-abs-boundaries\lib\site-packages\quart\app.py", line 1512, in full_dispatch_
request
result = await self.dispatch_request(request_context)
File "C:\Users\brend\miniconda3\envs\ms-abs-boundaries\lib\site-packages\quart\app.py", line 1557, in dispatch_reque
st
return await self.ensure_async(handler)(**request_.view_args)
File "C:\Users\brend\miniconda3\envs\ms-abs-boundaries\lib\site-packages\quart\utils.py", line 66, in _wrapper
result = await loop.run_in_executor(
File "C:\Users\brend\miniconda3\envs\ms-abs-boundaries\lib\concurrent\futures\thread.py", line 58, in run
result = self.fn(*self.args, **self.kwargs)
File "C:\Users\brend\Documents\GitHub\ms-abs-boundaries\src\TryLogging.py", line 15, in failme
raise Exception("Fake exception")
Exception: Fake exception
Only the exception is logged and the other success request is not logged.
How can I enable all requests (including other arbitrary info log events) to be logged when running in Hypercorn?
Hypercorn version: 0.13.2
Quart version: 0.16.2
NOTE: it needs to write to an external log system, not local logging file, and that external log is configured in the real version of the app. But getting it to show in the console is enough for testing.
Logs emitted by your application code would still be logged. What differs when you move from running with Quart to Hypercorn is that you no longer have the quart.serving logger which produced those messages you referred to.
To get similar behavior with Hypercorn, you can configure it to direct access log to stdout by setting accesslog to -.
I am trying to POST request from my flutter application to the Flask REST API, testing API with POST MAN has no problem, but on flutter I am getting error in flutter like this:
I/flutter ( 6378): FormatException: Unexpected character (at character 1)
I/flutter ( 6378):
I/flutter ( 6378): ^
and in Flask APP like this:
[2020-01-23 11:42:32,517] ERROR in app: Exception on /cards [POST]
Traceback (most recent call last):
File "/home/shaukat/.local/lib/python3.7/site-packages/flask/app.py", line 2311, in wsgi_app
response = self.full_dispatch_request()
File "/home/shaukat/.local/lib/python3.7/site-packages/flask/app.py", line 1834, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/shaukat/.local/lib/python3.7/site-packages/flask/app.py", line 1737, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/shaukat/.local/lib/python3.7/site-packages/flask/_compat.py", line 36, in reraise
raise value
File "/home/shaukat/.local/lib/python3.7/site-packages/flask/app.py", line 1832, in full_dispatch_request
rv = self.dispatch_request()
File "/home/shaukat/.local/lib/python3.7/site-packages/flask/app.py", line 1818, in dispatch_request
return self.view_functionsrule.endpoint
File "/home/shaukat/Projects/udemy flask rest API and python/rest-api-sections-master/section3/app.py", line 19, in create_card
'id': request_data["id"],
TypeError: 'NoneType' object is not subscriptable
127.0.0.1 - - [23/Jan/2020 11:42:32] "POST /cards HTTP/1.1" 500 -
My code in flutter:
Future<void> addNewCard(NewCard product) async {
const url = 'http://10.0.2.2:5000/cards';
try {
final response = await http.post(
url,
body: json.encode({
'id': product.id,
'cardNo': product.cardNo,
'cardType': product.cardType,
'amount': product.amount,
}),
);
final newProduct = NewCard(
id: json.decode(response.body)['id'],
cardNo: product.cardNo,
cardType: product.cardType,
amount: product.amount,
);
print(newProduct);
_newCard.add(product);
// _items.insert(0, newProduct); // at the start of the list
notifyListeners();
} catch (error) {
print(error);
throw error;
}}
code in python Flask:
#app.route('/cards', methods=['POST'])
def create_card():
request_data = request.get_json()
new_cards = {
'id': request_data["id"],
'cardNo': request_data["cardNo"],
'cardType': request_data["cardType"],
'amount': request_data["amount"],
}
cards.append(new_cards)
return jsonify(cards)
I eventually found the solution in a comment of this post Flutter POST request body not sent
I had to add headers: {"Content-Type": "application/json"}
in my post request. thanks for your help
line 19, in create_card 'id': request_data["id"], TypeError: 'NoneType' object is not subscriptable
As you see the server is unable to get the data / parse it.
I'd suggest to debug it inside the REST server and check if you are even receving the values..
I understand that postman works for you, but once you understand what are you even getting # the server it will be easier to fix what flutter sends.
my guess is that product.id (flutter code) is an int and not a string..
please send a more detailed debug information to help resolve this.
good luck.
Using a python script for posting articles on WordPress website. That was working fine till few days. Now , its returning error related to 409 conflict.
Unable to track the reason as there is no change in code from my side.
Traceback (most recent call last):
File "/home/vikas/anaconda3/lib/python3.7/site-packages/wordpress_xmlrpc/base.py", line 24, in __init__
self.supported_methods = self.server.mt.supportedMethods()
File "/home/vikas/anaconda3/lib/python3.7/xmlrpc/client.py", line 1112, in __call__
return self.__send(self.__name, args)
File "/home/vikas/anaconda3/lib/python3.7/xmlrpc/client.py", line 1452, in __request
verbose=self.__verbose
File "/home/vikas/anaconda3/lib/python3.7/xmlrpc/client.py", line 1154, in request
return self.single_request(host, handler, request_body, verbose)
File "/home/vikas/anaconda3/lib/python3.7/xmlrpc/client.py", line 1187, in single_request
dict(resp.getheaders())
xmlrpc.client.ProtocolError: <ProtocolError for www.indiandefencenews.co.in/xmlrpc.php: 409 Conflict>
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "t.py", line 16, in <module>
client = Client('https://www.indiandefencenews.co.in/xmlrpc.php','user','password')
File "/home/vikas/anaconda3/lib/python3.7/site-packages/wordpress_xmlrpc/base.py", line 27, in __init__
raise ServerConnectionError(repr(e))
wordpress_xmlrpc.exceptions.ServerConnectionError: <ProtocolError for www.indiandefencenews.co.in/xmlrpc.php: 409 Conflict>
My Code for the same is :
import urllib.request
import random
import csv
import os
import re
from wordpress_xmlrpc import Client, WordPressPost
from wordpress_xmlrpc.compat import xmlrpc_client
from wordpress_xmlrpc.methods import media, posts
client = Client('https://www.website.com/xmlrpc.php','User','password')
# prepare metadata
data = {
'name': 'picture.jpg',
'type': 'image/jpeg', # mimetype
}
with open(filename, 'rb') as img:
data['bits'] = xmlrpc_client.Binary(img.read())
response = client.call(media.UploadFile(data))
attachment_id = response['id']
post = WordPressPost()
post.title = title
post.content = text
post.post_status = 'publish'
post.thumbnail = attachment_id
post.id = client.call(posts.NewPost(post))
PID=post.id
print ('Success')
strn=str(num)
url = url.replace(strn,'')
print (strn)
strn=int(num)+1
url=url+str(strn)
print (url)
I have the need to reach a page using client certificate with pyppeteer,
i have seen that its possible with puppeteer itself here,
but my attempts lead to an invalid state errror with python3. Im not sure whether my attempt is entirely correct, but it follows the spirit of the issue comment in puppeteer. I would expect it to be possible, hence my attempts, here is the error:
[E:pyppeteer.connection] connection unexpectedly closed
Task exception was never retrieved
future: <Task finished coro=<Connection._async_send() done, defined at /home/data/experim/jaenv/lib/python3.6/site-packages/pyppeteer/connection.py:69> exception=InvalidStateError('invalid state',)>
Traceback (most recent call last):
File "/home/data/experim/jaenv/lib/python3.6/site-packages/pyppeteer/connection.py", line 73, in _async_send
await self.connection.send(msg)
File "/home/data/experim/jaenv/lib/python3.6/site-packages/websockets/protocol.py", line 467, in send
yield from self.write_frame(True, OP_TEXT, data.encode('utf-8'))
File "/home/data/experim/jaenv/lib/python3.6/site-packages/websockets/protocol.py", line 919, in write_frame
yield from self.ensure_open()
File "/home/data/experim/jaenv/lib/python3.6/site-packages/websockets/protocol.py", line 646, in ensure_open
) from self.transfer_data_exc
websockets.exceptions.ConnectionClosed: WebSocket connection is closed: code = 1006 (connection closed abnormally [internal]), no reason
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/data/experim/jaenv/lib/python3.6/site-packages/pyppeteer/connection.py", line 79, in _async_send
await self.dispose()
File "/home/data/experim/jaenv/lib/python3.6/site-packages/pyppeteer/connection.py", line 170, in dispose
await self._on_close()
File "/home/data/experim/jaenv/lib/python3.6/site-packages/pyppeteer/connection.py", line 153, in _on_close
f'Protocol error {cb.method}: Target closed.', # type: ignore
asyncio.base_futures.InvalidStateError: invalid state
This is the attempt that leads to the above error:
import asyncio
from pyppeteer import launch
from pyppeteer.network_manager import Request
import requests
async def interceptor(interceptReq, cert,key):
res = requests.get(interceptReq.url , cert=('../../widshared/certexp.cer','../../widshared/certpriv.pem'))
if not res.ok:
return await interceptReq.abort('connectionrefused')
else:
return await interceptReq.respond({
'status': res.status_code,
'headers': res.headers,
'body': res.content
})
async def main():
browser = await launch(headless = True )
page = await browser.newPage()
await page.setRequestInterception(True)
with open("../../widshared/certexp.cer", 'r') as cr:
cert = cr.read()
with open("../../widshared/certpriv.pem", 'r') as cr:
key = cr.read()
page.on('request', lambda interceptReq: asyncio.ensure_future(interceptor(interceptReq, cert, key )) )
await page.goto('https://client.badssl.com')
await page.screenshot({'path': 'clientbadssl.png'})
await browser.close()
asyncio.get_event_loop().run_until_complete(main())