I am trying to configure Google Cloud Functions to place an order when the function is triggered.
I have mentioned kiteconnect in the requirements.txt file
But the function doesn't get deployed. throws an error "Unknown resource type".
FULL ERROR MESSAGE:
Deployment failure: Build failed: {"error": {"canonicalCode": "INVALID_ARGUMENT", "errorMessage": "`pip_download_wheels` had stderr output:\nCommand \"python setup.py egg_info\" failed with error code 1 in /tmp/pip-wheel-97dghcl9/logging/\n\nerror: `pip_download_wheels` returned code: 1", "errorType": "InternalError", "errorId": "67DBDBF3"}}
Does anyone have any experience dealing with cloud functions to place a trading order on zerodah?
Following is the function that i have tried:
import logging
from kiteconnect import KiteConnect
logging.basicConfig(level=logging.DEBUG)
kite = KiteConnect(api_key="xxxxxxxxxxxxxxxxxxxxxxxx")
# Redirect the user to the login url obtained
# from kite.login_url(), and receive the request_token
# from the registered redirect url after the login flow.
# Once you have the request_token, obtain the access_token
# as follows.
data = kite.generate_session("xxxxxxxxxxxxxxxxxxxxxxxxx", secret="xxxxxxxxxxxxxxxxxxxxxxxxxx")
kite.set_access_token(data["xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"])
# Place an order
def orderPlace():
order_id = kite.place_order(
variety=kite.VARIETY_REGULAR,
exchange=kite.EXCHANGE_NSE,
tradingsymbol="INFY",
transaction_type=kite.TRANSACTION_TYPE_BUY,
quantity=1,
product=kite.PRODUCT_CNC,
order_type=kite.ORDER_TYPE_MARKET
)
logging.info("Order placed. ID is: {}".format(order_id))
except Exception as e:
logging.info("Order placement failed: {}".format(e.message))
Content of requirements.txt file:
# Function dependencies, for example:
# package>=version
kiteconnect
The error indicates that one of your dependencies is uninstallable.
It looks like the kiteconnect dependency is currently incompatible with Python 3.7, which is the Python version Cloud Functions uses in it's runtime: https://github.com/zerodhatech/pykiteconnect/issues/55
You'll need to wait until the maintainers release a new version that is compatible with Python 3.7.
Related
I am working on a python project which includes using the Youtube\Google API, accessing public playlists.
The code works fine in the Pycharm IDE but after using Pyinstaller to build it into an .exe file, it crashes and prints 'Crashed at youtube build stage'
from googleapiclient.discovery import build
try:
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = json_path
credentials = google.oauth2.service_account.Credentials.from_service_account_file(json_path)
print("credentials=",credentials)
youtube = build(serviceName='youtube', version='v3', developerKey=yt_api_key, num_retries=3,credentials=credentials)
except Exception as e:
print(f"Crashed at youtube build stage \n\nError: {e}")
try:
youtube_playlist=youtube.playlists().list(part='contentDetails,id',id=youtube_playlist_id)
youtube_playlist=youtube_playlist.execute()
except Exception as e:
print(e,"\nERROR HERE")
When running on the IDE the build succeeds, but fails at the 2nd try except section.
The error given is :
('invalid_scope: Invalid OAuth scope or ID token audience provided.', {'error': 'invalid_scope', 'error_description': 'Invalid OAuth scope or ID token audience provided.'})
I looked at the google API and the playlists() method and I didn't find any place to use the Oauth credentials there.
When running on the EXE it simply prints :
Crashed at youtube build stage
Error: name: youtube version: v3
According the the build() documentation found here https://googleapis.github.io/google-api-python-client/docs/epy/googleapiclient.discovery-module.html#build
I found that the function raises an error when it can't create an mTLS connection.
Why can't it do so when the code is ran from an .exe file but manages when called from the IDE?
I thought the .exe created with Pyinstaller would work as it does on Pycharm, but it appears not to.
Not sure why TLS fails to set up.
Edit: added credentials and Oauth2 and another error appears.
It manages to build it but right afte
I'm running Django on a compute engine using Docker. I would like to know how to check the error in the Error Report when the application encounters an error like Cloud run.
I'm looking at how to set up an Error Report in Python. https://github.com/googleapis/python-error-reporting/tree/main/samples/snippets/fluent_on_compute
Looking at this sample, it looks like I need to raise an exception and run report (traceback.format_exc ()) to use the Error Report.
Sample code
def simulate_error():
fluent.sender.setup('myapp', host='localhost', port=24224)
def report(ex):
data = {}
data['message'] = '{0}'.format(ex)
data['serviceContext'] = {'service': 'myapp'}
# ... add more metadata
fluent.event.Event('errors', data)
# report exception data using:
try:
# simulate calling a method that's not defined
raise NameError
except Exception:
report(traceback.format_exc())
When I run Django, I get an error other than using try: execpt.
How can I display such errors in the Error Report?
Please let me know if there is any good way. thank you.
Django provides an option to define custom exception handler.
You can define custom exception handler as show below,
from google.cloud import error_reporting
from rest_framework.views import exception_handler
# Initialize Error reporting client
client = error_reporting.Client()
def custom_exception_handler(exc, context):
# Call REST framework's default exception handler first,
# to get the standard error response.
response = exception_handler(exc, context)
# Send error to Error Reporting
client.report(response)
return response
In your settings file add the below configuration,
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'
}
To install google cloud error reporting library, use the below command
pip install google-cloud-error-reporting
For reference on setting up Error reporting in python, refer to this
I'm trying to send an email using SendGrid within Azure Machine Learning. This is initially just a basic test email to ensure it is working correctly.
The steps I have taken:
Pip installed SendGrid;
Zipped the SendGrid download and uploaded as a dataset to AML platform;
Attempted to run the example SendGrid Python code (which can be seen below):
I have copied steps in similar posts concerning uploading modules to AML here and here as well as ensuring the correct settings for the SendGrid API key were established on setup here.
def azureml_main():
import sendgrid
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail
message = Mail(
from_email='xxx#xyz.com',
to_emails='xxx#xyz.com',
subject='Sending with Twilio SendGrid is Fun',
html_content='<strong>and easy to do anywhere, even with Python</strong>')
try:
sg = SendGridAPIClient(os.environ.get('SG API Code'))
response = sg.send(message)
print(response.status_code)
print(response.body)
print(response.headers)
except Exception as e:
print(e)
No error message is returned in the terminal. To me this indicates there weren't any issues with the code, yet no emails have been received/sent.
python ScheduleRun.py
azureuser#will1:~/cloudfiles/code/Users/will/Schedule$
azureuser#will1:~/cloudfiles/code/Users/will/Schedule$ python ScheduleRun.py
azureuser#will1:~/cloudfiles/code/Users/will/Schedule$
Twilio SendGrid developer evangelist here.
When you run the code nothing is printed, which is concerning as neither the success or error prints are called.
If the code you have shared is the entirety of the file then I think the code is simply not running. You have defined a function but you have not called the function itself.
Try calling azureml_main() on the last line of the file:
print(response.headers)
except Exception as e:
print(e)
azureml_main()
One other thing that concerns me is this line:
os.environ.get('SG API Code')
It looks as though you intend to actually place your SG API Key in the call to os.environ.get. Instead, that string should be the identifier for an environment variable that you have set. For example, you should set the SendGrid API key as an environment variable called SENDGRID_API_KEY and then in your code fetch the API key by calling os.environ.get("SENDGRID_API_KEY"). Check out this post on working with environment variables in Python for more.
I am using the below piece of of code :
from azure.identity import AzureCliCredential
from azure.graphrbac import GraphRbacManagementClient
credential = AzureCliCredential()
tenant_id = ""
graph_client = GraphRbacManagementClient(credential,tenant_id)
users = graph_client.users.list()
for i in users:
print (i.user_principal_name)
When I am using the above code its giving me the below error :
AttributeError: 'AzureCliCredential' object has no attribute 'signed_session'
If I remove the iteration for paged context of the users . then there is no error and i get output as :
<azure.graphrbac.models.user_paged.UserPaged object at 0x0000025125C1B250>
Please help in getting the list of the users from the paged context.
I tried using the same code but authenticating with service principal . I got an error, that insufficient privileges as the GraphrbacManagementClient uses the Azure AD graph legacy API permissions to get the users which is deprecated and I couldn't add the permissions for the service principal.
As a Solution I used msgraph-core module to get the issue fixed which use Microsoft Graph API.
You can install the package using the below command:
pip install msgraph-core
After installation you can use the below code :
from azure.identity import ClientSecretCredential
from msgraph.core import GraphClient
clientid= "clientID or AppID"
clientsecret = "secret for the service principal"
tenantid = "tenantid"
credentials=ClientSecretCredential(tenant_id=tenantid,client_id=clientid,client_secret=clientsecret)
graph_client = GraphClient(credential=credentials)
users = graph_client.get('/users?$select=userPrincipalName,id')
print(users.json())
Output:
I'm using the following Python code from Slack's "Migrating to 2.x" github docs
from slackclient import SlackClient
slack_token = os.environ["SLACK_API_TOKEN"]
client = SlackClient(slack_token)
def say_hello(data):
if 'Hello' in data['text']:
channel_id = data['channel']
thread_ts = data['ts']
user = data['user']
client.api_call('chat.postMessage',
channel=channel_id,
text="Hi <#{}>!".format(user),
thread_ts=thread_ts
)
if client.rtm_connect():
while client.server.connected is True:
for data in client.rtm_read():
if "type" in data and data["type"] == "message":
say_hello(data)
else:
print "Connection Failed"
For the SLACK_API_TOKEN, I am using the Bot User OAuth Access Token for my app, found here:
The error I am getting is the following:
Failed RTM connect
Traceback (most recent call last):
File "/Users/.../slackbot/slackbot_env/lib/python3.8/site-packages/slackclient/client.py", line 140, in rtm_connect
self.server.rtm_connect(use_rtm_start=with_team_state, **kwargs)
File "/Users/.../slackbot/slackbot_env/lib/python3.8/site-packages/slackclient/server.py", line 168, in rtm_connect
raise SlackLoginError(reply=reply)
slackclient.server.SlackLoginError
Connection Failed
Why am I getting this error?!?!?!
Other context:
I am on a Mac, unlike others who have had issues online using Windows
machines.
I am running the code locally, in a virtual env, via
python script.py in my terminal.
I last successfully ran this in December, and have seen that Slack dropped support for the RTM API (?) Dec 31st 2019?
The app has been reinstalled to my workspace, and the keys did not change.
I think it may be something I need to configure/change/set/refresh on the api.slack.com/apps side, since it broke without any code changes occurring.
Why am I focusing on debugging the example for 1.x? My code was previously working using rtm_connect / 1.x using the same commands as the example code, and without any code changes it has stopped working. My code and the example code yield the same errors, so I'm using the sample code to make debugging easier. I'd like to fix this before starting the process of migrating to 2.x, so I can start with working code before embarking on a long series of changes that can introduce their own errors.
I do not think this issue is related to the Bot User OAuth Access Token, in my view you are using the right one (xoxb-). However, this issue might be related to the Slack App. Note that RTM isn't supported for the new Slack App granular scopes (see python client issue #584 and node client issue #921). If you want to use RTM, you should create rather a classic slack app with the OAuth Scope bot.
I not sure if this is the reason, but I ran into the same issues before.
The answer I found on the Slack Github is that new xoxob-* doesn't support RTM.
Please reference this web:
- https://github.com/slackapi/python-slackclient/issues/326.
So I use my OAuth Access Token instead of Bot User OAuth Access Token.