I want to test a simple Ethereum smart contract
ganache prints accounts in lower-case and web3 gives me an error:
web3.exceptions.InvalidAddress: ('Web3.py only accepts checksum addresses. The software that gave you this non-checksum address should be considered unsafe, please file it as a bug on their platform. Try using an ENS name instead. Or, if you must accept lower safety, use Web3.toChecksumAddress(lower_case_address).', '0xfcad0b19bb29d4674531d6f115237e16afce377c')
I then convert the address to mixed address using:
Web3.toChecksumAddress(the_lower_case_ganache_address)
and it rises an error:
File "/usr/local/lib/python3.7/site-packages/web3/contract.py", line 1385, in call_contract_function
raise BadFunctionCallOutput(msg) from e
web3.exceptions.BadFunctionCallOutput: Could not transact with/call contract function, is contract deployed correctly and chain synced?
127.0.0.1 - - [25/Jan/2019 21:35:21] "POST /blockchain/user HTTP/1.1" 500 -
it's my python code:
def check_gender(data):
valid_list = ["male", "female"]
if data not in valid_list:
raise ValidationError(
'Invalid gender. Valid choices are'+ valid_list
)
class UserSchema(Schema):
name = fields.String(required=True)
gender = fields.String(required=True, validate=check_gender)
app = Flask(__name__)
# api to set new user every api call
#app.route("/blockchain/user", methods=['POST'])
def transaction():
w3.eth.defaultAccount = w3.eth.accounts[0]
with open("data.json", 'r') as f:
datastore = json.load(f)
abi = datastore["abi"]
contract_address = datastore["contract_address"]
# Create the contract instance with the newly-deployed address
user = w3.eth.contract(
address=contract_address, abi=abi,
)
body = request.get_json()
result, error = UserSchema().load(body)
if error:
return jsonify(error), 422
tx_hash = user.functions.setUser(
result['name'], result['gender']
)
tx_hash = tx_hash.transact()
# Wait for transaction to be mined...
w3.eth.waitForTransactionReceipt(tx_hash)
user_data = user.functions.getUser().call()
return jsonify({"data": user_data}), 200
if __name__ == '__main__':
app.run()
`
and the json file:
{
"abi": [
{
"constant": false,
"inputs": [
{
"name": "name",
"type": "string"
},
{
"name": "gender",
"type": "string"
}
],
"name": "setUser",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": false,
"inputs": [],
"name": "getUser",
"outputs": [
{
"name": "",
"type": "string"
},
{
"name": "",
"type": "string"
}
],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
}
],
"contract_address": "0xFCAd0B19bB29D4674531d6f115237E16AfCE377c"
}
The error is stating that Ganache cannot find a deployed contract to interact with.
Your code seems valid, but the error likely occurs on this line:
tx_hash = user.functions.setUser(
result['name'], result['gender']
)
The code attempts to set the user, but cannot find a contract to interact with (even if the ABI and contract instance are valid).
If you are using Ganache, it is likely that you are redeploying the contract each time you run the code, so the following line will likely not be working, provided you are pulling from a static file:
contract_address = datastore["contract_address"]
You will need to dynamically get the contract address from Ganache if you are deploying it each time.
Related
I'm using notion-sdk-py package to interact with Notion SDK.
I want to change property type multi_select -> rich_text (text)
Prop is multi_select type property
My code:
from notion_client import Client
notion = Client(auth=settings["auth"])
any_db = notion.databases.query(settings["databases"]["any"])
page = any_db["results"][0]
notion.pages.update(
page["id"],
properties={"Prop": {"type": "rich_text", "rich_text": []}}
)
# Also tried this
notion.pages.update(
order["id"],
properties={
"Prop": {
"type": "rich_text",
"rich_text": [{
"type": "text",
"text": {
"content": "yemreak.com"
},
"href": None
}]
}
}
)
# Both of them raise same error
# notion_client.errors.APIResponseError: Prop is expected to be multi_select.
Additional Resources
Updating Schema Object ~ Notion API
All Rich text ~ Notion API
I'm having trouble loading data from a json file in my blender add-on, it's throwing me a fatal error and I don't know how to fix it. I looked up the error multiple times but the problems never apply to my code, can anyone help me fix it?
this is the json file (default.json)
{
"viewport": "solid",
"lighting": {
"type": "studio",
"lighting file": "Basic",
"world space lighting": {
"enabled": false
}
},
"color": "OBJECT",
"background": "THEME",
"backface culling": false,
"x-ray": {
"enabled": false
},
"shadow": {
"enabled": false
},
"cavity": {
"enabled": true,
"type": "world",
"ridge": "${BindValue: RIDGE}",
"valley": "${BindValue: VALLEY}"
},
"depth of field": false,
"outline": {
"enabled": false
},
"specular lighting": false
}
this is the function to load it
def loadPreset(location):
with open(location) as json_file:
print(json.load(json_file))
data = json.load(json_file)
with data["lighting"] as lighting:
if lighting["type"] == "studio":
bpy.context.space_data.shading.light = 'STUDIO'
bpy.context.space_data.shading.studio_light = lighting["lighting file"]
with lighting["world space lighting"] as world_space_lighting:
bpy.context.space_data.shading.use_world_space_lighting = world_space_lighting
if world_space_lighting:
bpy.context.space_data.shading.studiolight_rotate_z = world_space_lighting["rotation"]
bpy.context.space_data.shading.color_type = data["color"]
bpy.context.space_data.shading.background_type = data["background"]
bpy.context.space_data.shading.show_backface_culling = data["backface culling"]
bpy.context.space_data.shading.show_xray = data["x-ray"]["enabled"]
if data["x-ray"]["enabled"]:
bpy.context.space_data.shading.xray_alpha = data["x-ray"]["alpha"]
and this operator to call it
class VPM_DP_DEFAULT(bpy.types.Operator):
bl_label = "default"
bl_idname = "view.default_display"
def execute(self, context):
data.currentViewport = "default"
import pathlib
loadPreset(str(pathlib.Path(__file__).parent.absolute()) + "\\viewportPresets\\basic\\default.json")
return {'FINISHED'}
but when I click the button linked to the operator, it gives me this error...
I looked around to see how to fix this, the problem is usually checking for a key that doesn't exist, but my code never checks for a key called 'presets'
Why flagSelectTask is working sometimes and sometimes not?
In the code below, When I type /reminder in chatbot the flag should be set to True and when I open webview it should check the condition and result accordingly. But If I clicks multiple times after closing a webview It returns either if block or else block. Why this is happening?
class Bot:
flagSelectTask = {}
def handleTextMessage(self,recipientID,messagingEvent):
if textMessage.lower() == '/reminder':
Bot.flagSelectTask[recipientID] = True # Select Task Webview Access Permission Granted
return self.selectTaskWebView(recipientID)
def selectTaskWebView(self,assignerID):
messageData = {
"recipient":{
"id":assignerID
},
"message": {
"attachment": {
"type": "template",
"payload": {
"template_type": "generic",
"elements": [
{
"title": "Please Select a Task",
"buttons": [
{
"type": "web_url",
"title": "Select",
"url": f"url.com/select-task/{assignerID}",
"webview_height_ratio": "tall",
"messenger_extensions": "true",
},
],
},
],
},
}}}
return self.sendAPI(messageData)
bot = Bot()
#app.route('/select-task/<string:assignerID>',methods=['GET'])
def selectTaskView(assignerID):
if (assignerID in bot.flagSelectTask) and (bot.flagSelectTask[assignerID]):
Task = bot.loadTasks(assignerID)
log(Task)
if len(Task)!=0:
return render_template('tasks.html',tasks=Task)
else:
return '<b>You have not assigned any task yet</b>'
else:
return '<h1> Thank You. Please Restart If you want to send a reminder again.</h1>'
So I'm pretty new to implementing flask-restplus and I have encountered this road block.
I have read the restplus docs over and over again and followed several exampled. But the behavior that I'm facing is very much different from what is supposed to be.
So I have a model that is supposed to be a list of objects of another model (returned from the function drone_model()).
drones_list = api.model('drones_list', {
'items': fields.List(fields.Nested(drone_model())),
'message':fields.String(''),
'code': fields.Integer('')
})
Everything works fine, no errors. But when I try the API (http://127.0.0.1:5000/datamine/v2/drones), as a response I get the Marshalling model back instead of the data itself. If I print the data, it gets printed, but for some reason in the web, the restplus model is returned.
Below I have the code that I had written. If I take the marshal_with decorator off, then the data is returned just fine.
#api.route('/')
class DronesList(Resource):
#api.marshal_with(drones_list, envelope='data')
#api.response(200, 'All drones successfully fetched!')
def get(self):
"""
Get all drones!.
"""
from app.utils.common import get_start_end_date_from_request
start_date, end_date = get_start_end_date_from_request(request)
drones = []
for drone in Drone.objects:
drones.append({
'id': str(drone.id),
'serial_id': drone.serial_id,
'maintenances': [],
'status': get_dynamic_status(drone, start_date, end_date),
'picture_url': drone.asset.picture_url,
'manufacturer': drone.asset.manufacturer,
'model_name': drone.asset.model_name,
'drone_type': drone.asset.drone_type,
'payload_type': drone.asset.payload_type,
'asset_url': drone.get_url(drone.id)
})
success = ClientSuccessFunctionClass('All drones successfully fetched!', 200, drones)
return (success.to_dict())
These are the outputs on the browser:
1. Without the marshal decorator:
{
"data": {
"items": [
{
"id": "5aeafcb93a33683f73827e91",
"serial_id": "Drone 1",
"maintenances": [],
"status": "Decommissioned",
"picture_url": "some img url",
"manufacturer": "DJI",
"model_name": "Phantom 4 Pro",
"drone_type": "Quadcopter",
"payload_type": "RGB Camera",
"asset_url": "http://127.0.0.1:5000/datamine/v1/drones/5aeafcb93a33683f73827e91"
},
{
"id": "5aeaff374f85747f90df2714",
"serial_id": "Drone 2",
"maintenances": [],
"status": "Available",
"picture_url": "sime url",
"manufacturer": "DJI",
"model_name": "Phantom 4",
"drone_type": "Quadcopter",
"payload_type": "RGB Camera",
"asset_url": "http://127.0.0.1:5000/datamine/v1/drones/5aeaff374f85747f90df2714"
}
],
"message": "All drones successfully fetched!",
"code":200
}
}
2. With the marshal decorator:
{
"data": {
"items": [
{
"id": "Id of Drone",
"serial_id": "Name of Drone",
"status": "Status of Drone",
"maintenances": null,
"picture_url": "Picture URL",
"manufacturer": "Manufacturer of Drone",
"model_name": "Model name of Drone",
"drone_type": "Type of Drone",
"payload_type": "Payload type of Drone",
"asset_url": "Asset URL of Drone"
}
],
"message": "",
"code": ""
}
}
It would be really helpful if someone could tell me what I'm doing wrong as I need to recive the output as the one shown in snippet of the output without the decorator.
Thank you.
Here is a diagram showing invocation order from top to bottom to help make sense of what is happening:
get()
→ api.response(200, 'All drones successfully fetched!') # documents the response
→ api.marshal_with(drones_list, envelope='data')` # returns marshalled dict
The result from invoking get is passed to the api.response decorator function whose result is passed on to api.marshal_with decorator function.
Looking at the shape of the dictionary returned from invoking get()
{
data {
items [
{
id,
serial_id,
maintenances,
status,
picture_url,
manufacturer,
model_name,
drone_type,
payload_type,
asset_url
}
],
message,
code
}
}
The message and code in the response are nested inside of the data.
You need to model the data appropriately, to be able to marshal it. This can be done by passing an argument for what field to look up in the marshal dictionary.
drones_list = api.model('drones_list', {
'items': fields.List(fields.Nested(drone_model()), attribute='data.items'),
'message':fields.String(attribute='data.message'),
'code': fields.Integer(attribute='data.code')
})
As you can see, it's pretty redundant applying the api.marshal_with decorator function on the view given that it's only unnests then nests the result in data field.
I am trying to get the output of Watson Assistant into a variable. So as far as I have searched, i need to get the "output" and "text" part of the json (at first it is a dict, but then we parse it to a json). But I cannot seem to get it:
I have searched in these 2 questions already:This one for watson This one for parsing the json
The code is really simple: accessing to my bot, and inputting "trips". I've taken out the api and workspace, but I have them (obviously).
if __name__ == '__main__':
assistant = watson_developer_cloud.AssistantV1(
iam_apikey='{YOUR API HERE}',
version='2018-09-20',
url='https://gateway-syd.watsonplatform.net/assistant/api'
)
response = assistant.message(
workspace_id='{YOUR WORKSPACE HERE}',
input={
'text': 'trips'
}
).get_result()
fullResponse=json.dumps(response, indent=2)
print(fullResponse)
print("testing to print the output: ")
respuesta=json.dumps(response, indent=2)
#print(respuesta['output'][0]['text'])
print(respuesta['output']['text'])
And the output:
Traceback (most recent call last):
"intents": [
File "C:/Users/.PyCharmCE2018.3/config/scratches/pruebaMain.py", line 105, in <module>
{
print(respuesta['output']['text'])
"intent": "trips",
TypeError: string indices must be integers
"confidence": 1
}
],
"entities": [],
"input": {
"text": "trips"
},
"output": {
"generic": [
{
"response_type": "text",
"text": "We got trips to different countries! Type continents to know more!"
}
],
"text": [
"We got trips to different countries! Type continents to know more!"
],
"nodes_visited": [
"node_2_1544696932582"
],
"log_messages": []
},
"context": {
"conversation_id": "{took it out for privacy}",
"system": {
"initialized": true,
"dialog_stack": [
{
"dialog_node": "root"
}
],
"dialog_turn_counter": 1,
"dialog_request_counter": 1,
"_node_output_map": {
"node_2_1544696932582": {
"0": [
0
]
}
},
"branch_exited": true,
"branch_exited_reason": "completed"
}
}
}
testing to print the output:
Process finished with exit code 1
So I want to get the answer of "We got trips to different countries! Type continents to know more!". I have read the documentation of the python API and some more info (https://github.com/IBM-Cloud/watson-conversation-variables) of but can't seem to find anything. I also tried accessing the json variable with $but did not work.
You don't have to use json.dumps here, you can directly use the response JSON returned from the service as shown in the code snippet below
import watson_developer_cloud
if __name__ == '__main__':
assistant = watson_developer_cloud.AssistantV1(
iam_apikey='APIKEY',
version='2018-09-20',
url='https://gateway.watsonplatform.net/assistant/api'
)
response = assistant.message(
workspace_id='WORKSPACE_ID',
input={
'text': 'trips'
}
).get_result()
print(response)
print(response['output']['text'][0])