Import data from Zoho Analytics to Python - python

I'm trying to connect Zoho Analytics and Python via Zoho client library here: https://www.zoho.com/analytics/api/#python-library
I downloaded the client library file but now have no idea how to use it. What I want to do is importing data from Zoho Analytics to Python and the suggested code on Zoho is:
from __future__ import with_statement
from ReportClient import ReportClient
import sys
from __future__ import with_statement
from ReportClient import ReportClient
import sys
class Sample:
LOGINEMAILID="abc#zoho.com"
AUTHTOKEN="************"
DATABASENAME="Workspace Name"
TABLENAME="Table Name"
rc = None
rc = ReportClient(self.AUTHTOKEN)
def importData(self,rc):
uri = rc.getURI(self.LOGINEMAILID,self.DATABASENAME,self.TABLENAME)
try:
with open('StoreSales.csv', 'r') as f:
importContent = f.read()
except Exception,e:
print "Error Check if file StoreSales.csv exists in
the current directory"
print "(" + str(e) + ")"
return
impResult = rc.importData(uri,"APPEND",importContent,None)
print "Added Rows :" +str(impResult.successRowCount) + " and Columns :"
+ str(impResult.selectedColCount)
obj = Sample()
obj.importData(obj.rc)
How do I make from ReportClient import ReportClient work?
Also, how does rc = ReportClient(self.AUTHTOKEN) work if self wasn't predefined?

On the site you linked, you can download a zip file containing the file Zoho/ZohoReportPythonClient/com/adventnet/zoho/client/report/python/ReportClient.py. I'm not sure why it's so deeply nested, or why most of the folders contain an __init__.py file which only has #$Id$ in it.
You'll need to extract that file, and place it somewhere where your Python interpreter can find it. For more information about where Python will look for the module (ReportClient.py), see this question: How does python find a module file if the import statement only contains the filename?
Please note that the file is Python 2 code. You'll need to use a Python 2 interpreter, or convert it to Python 3 code. Once you've got it importing properly, you can use their API reference to start writing code with it: https://css.zohostatic.com/db/api/v7_m2/docs/python/

Related

what does "with open(os.path.join(os.path.dirname(os.path.abspath(\'__file__')) ,'.\\profile.json') as profile_json)" mean ? python

what does this line mean ?
Also I'm getting error in this line, The error says :
"unexpected character after line continuation character"
I'm new to this and I'm not able to resolve this.
Any help would be appreciated. Thank you
my code -
from ibm_watson import PersonalityInsightsV3
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from os.path import join, dirname
import json
import os
authenticator =
IAMAuthenticator('{api key')
personality_insights = PersonalityInsightsV3(version='2017-10-13',
authenticator=authenticator)
personality_insights.set_service_url('{url}')
with open(os.path.join(os.path.dirname(os.path.abspath(\'__file__'))
,'.\\profile.json')) as profile_json)
profile =personality_insights.profile(profile_json.read(),'application/json',
content_type='application/json', consumption_preferences=True,
raw_scores=True,get_result())
print(json.dumps(profile, indent=2))
There are so many Python syntax errors in your code it is hard to know where to begin.
So I am giving you a (corrected) sample from the API documentation: https://cloud.ibm.com/apidocs/personality-insights?code=python#profile
Take a note of the position and inclusion of \, :, and indentations. They are key to python syntax.
from ibm_watson import PersonalityInsightsV3
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from os.path import join, dirname
import json
authenticator = IAMAuthenticator('{apikey}')
personality_insights = PersonalityInsightsV3(
version='2017-10-13',
authenticator=authenticator
)
personality_insights.set_service_url('{url}')
with open(join(dirname(__file__), 'profile.json')) as profile_json:
profile = personality_insights.profile(
profile_json.read(),
'application/json',
content_type='application/json',
consumption_preferences=True,
raw_scores=True
).get_result()
print(json.dumps(profile, indent=2))
By the way, by including it in your question you have made your API key public.
When written correctly the line in question means: Open the file, found at this location as the variable profile_json, which if successful will be used in the indented code.
dirname(__file__)
is the directory location of the python file you are running.
join, constructs a platform independent file path. You shouldn't include directory separators because that would defeat the platform independence mantra. So in your case you are expecting the input profile.json to be in the same directory as your python code.

Lambda function - How to split python code across multiple files

Problem
I'm trying to split my python code for a lambda function across multiple files however any attempt to import the other relative modules throws an error for the top level module.
{
"errorMessage": "Unable to import module 'download_ga_data'"
}
What am I doing wrong? This feels like it should be super basic.
File structure layout (shown from root)
- download_ga_data.py
- [analytics]
- google.py (contains a single class)
- __init__.py
- [helpers]
- main.py (contains a single class)
- __init__.py
- {other libraries from site-packages}
Contents of download_ga_data.py
# import unicodecsv as csv
import os
# import path
from . import definitions
from analytics.google import GoogleAnalytics
from helpers.main import GoogleCloudStorageBucket
def lambda_handler(event, context):
print("test")
This as it stands will throw the error. If I comment out the three imports after os, then it will function correctly.
How should I correctly import these two modules, I feel like I'm missing something super basic.
Environment notes
This is all built on a the following lambda mimicking docker and uploaded straight into S3. All the files are 777 to bypass any permissions errors.
Ok finally solved this. The main tip I received to help with this was to wrap my load functions in a try except block:
try:
import definitions
from analytics.google import GoogleAnalytics
from cloud_helpers.main import GoogleCloudStorageBucket
except Exception as e:
error = str(e)
stacktrace = json.dumps(traceback.format_exc())
message = "Exception: " + error + " Stacktrace: " + stacktrace
err = {"message": message}
return respond(err)
def respond(err, res=None):
return {
"statusCode": "400" if err else "200",
"body": err["message"] if err else json.dumps(res),
"headers": {"Content-Type": "application/json"},
}
This then revealed the following error (which I irritatingly only have a screenshot of):
Which was then solved by switching to import definitions

How to decode python string

I have some code which I would like to be decoded but not having much luck in guessing what the codepage is, if any is being used. Any help would be much appreciated.
i am using python command line in windows 7 pc,if any python guru guide me how to decrypt and see the code thaat would be appreciated.
exec("import re;import base64");exec((lambda p,y:(lambda o,b,f:re.sub(o,b,f))(r"([0-9a-f]+)",lambda m:p(m,y),base64.b64decode("NTQgYgo1NCA3CjU0IDMKNTQgMWUKNTQgOQo1NCAxOAozZiAgICAgICA9IGIuMTAoKQoxNiAgID0gIjQzOi8vMTIuM2QvNGMvMWQuMjUuZi00ZC4zZSIKYSA9ICIxZC4yNS5mIgoyYSA4KDYpOgoJMzMgMy5jKCczYy4yZSglNTIpJyAlIDYpID09IDEKCjJhIDE1KDM1KToKCTUgPSAzLjQoMWUuNS4xYygnMTM6Ly8yZC8xZicsJzMwJykpCgkyMyA1CgkyMSA9IDcuMTQoKQoJMjEuMzgoIjEwIDI4IiwiMjAgMTAuLiIsJycsICczNiA0MCcpCgkxMT0xZS41LjFjKDUsICdlLjNlJykKCTM5OgoJCTFlLjFhKDExKQoJMWI6CgkJMmMKCQk5LmUoMzUsIDExLCAyMSkKCQkyID0gMy40KDFlLjUuMWMoJzEzOi8vMmQnLCcxZicpKQoJCTIzIDIKCQkyMS4zNCgwLCIiLCAiM2IgNDciKQoJCTE4LjQ4KDExLDIsMjEpCgkJCgkJMy41MygnMjIoKScpOyAKCQkzLjUzKCcyNigpJyk7CgkJMy41MygiNDUuZCgpIik7IAoJCTE5PTcuMzcoKTsgMTkuNTAoIjMyISIsIjJmIDNhIDQ5IDQxIDI5IiwiICAgWzI0IDQ2XTMxIDUxIDRhIDRlIDE3LjNkWy8yNF0iKQoJCSIiIgoJCTM5OgoJCQkxZS4xYSgxMSkKCQkxYjoKCQkJMmMKCQkJIzI3KCkKCQk0Mjo0NCgpCgkJIiIiCgoyYSAyYigpOgoJNGYgNGIgOChhKToKCQkxNSgxNikKCQoKCjJiKCk=")))(lambda a,b:b[int("0x"+a.group(1),16)],"0|1|addonfolder|xbmc|translatePath|path|script_name|xbmcgui|script_chk|downloader|scriptname|xbmcaddon|getCondVisibility|UpdateLocalAddons|download|supermax|Addon|lib|supermaxwizard|special|DialogProgress|INSTALL|website|SuperMaxWizard|extract|dialog|remove|except|join|plugin|os|addons|Installing|dp|UnloadSkin|print|COLOR|video|ReloadSkin|FORCECLOSE|Installer|Installed|def|Main|pass|home|HasAddon|SuperMax|packages|Brought|Success|return|update|url|Please|Dialog|create|try|Wizard|Nearly|System|com|zip|addon|Wait|been|else|http|quit|XBMC|gold|Done|all|has|You|not|sm|MP|By|if|ok|To|s|executebuiltin|import".split("|")))
The code is uglified. You can unobfuscate it yourself by executing the contents of exec(...) in your Python shell.
import re
import base64
print ((lambda p,y.....split("|")))
EDIT: As snakecharmerb says, it is generally not safe to execute unknown code. I analysed the code to find that running the insides of exec will only decrypt, and leaving off the exec itself will just result in a string. This procedure ("execute stuff inside exec") is by no means a generally safe method to decrypt uglified code, and you need to actually analyse what it does. But, at this point, I was asking you to trust my judgement, which, if it is wrong, theoretically could expose you to an attack. In addition, it seems you have problems getting it to run on your Python; so here's what I'm getting from the above:
import xbmcaddon
import xbmcgui
import xbmc
import os
import downloader
import extract
addon = xbmcaddon.Addon()
website = "http://supermaxwizard.com/sm/plugin.video.supermax-MP.zip"
scriptname = "plugin.video.supermax"
def script_chk(script_name):
return xbmc.getCondVisibility('System.HasAddon(%s)' % script_name) == 1
def INSTALL(url):
path = xbmc.translatePath(os.path.join('special://home/addons','packages'))
print path
dp = xbmcgui.DialogProgress()
dp.create("Addon Installer","Installing Addon..",'', 'Please Wait')
lib=os.path.join(path, 'download.zip')
try:
os.remove(lib)
except:
pass
downloader.download(url, lib, dp)
addonfolder = xbmc.translatePath(os.path.join('special://home','addons'))
print addonfolder
dp.update(0,"", "Nearly Done")
extract.all(lib,addonfolder,dp)
xbmc.executebuiltin('UnloadSkin()');
xbmc.executebuiltin('ReloadSkin()');
xbmc.executebuiltin("XBMC.UpdateLocalAddons()");
dialog=xbmcgui.Dialog(); dialog.ok("Success!","SuperMax Wizard has been Installed"," [COLOR gold]Brought To You By SuperMaxWizard.com[/COLOR]")
"""
try:
os.remove(lib)
except:
pass
#FORCECLOSE()
else:quit()
"""
def Main():
if not script_chk(scriptname):
INSTALL(website)
Main()

Flask not writing to file

I've been meaning to log all the users that visit the site to a file.
Using Flask for the backend.
I have not been able to get python to write to the file. Tried keeping exception handling to catch any errors that might be generated while writing. No exceptions are being raised.
Here is the part of the blueprint that should write to file.
from .UserDataCache import UserDataCache
udc = UserDataCache()
#main.route('/')
def index():
s = Suggestion.query.all()
udc.writeUsertoFile()
return render_template('suggestions.html', suggestions = s)
Here is the UserDataCache class:
from flask import request
from datetime import datetime
class UserDataCache():
def __init__(self):
pass
def writeUsertoFile(self):
try:
with open("userData.txt","a") as f:
f.write(str(datetime.now()) + " " + request.remote_addr + " " + request.url + " " + request.headers.get('User-Agent') + "\n")
except IOError,e:
print e
return
I recommend using an absolute path and verifying the permissions on that file. Something like /tmp/UserData.txt or another absolute path should work. The web server's user is what needs the permission to write to the file (www-data if you're using apache2 with Ubuntu, or check your web server's conf file to verify).
As far as why you're not seeing the exception you're catching, I see you're using print. If you're calling the app using a web browser, you'll need to send the error to something else, like a log file or flash it to the browser, or raise an error so it gets logged in the web server error log.
Is your python file name begins with uppercase? If so, try to modify it into lowercase.
I just came into the same problem and copied the exactly same code into two .py file. The only difference is their file name, one being 'Flask_test.py' and another being 'flask_for_test.py'. It's weird that 'Flask_test.py' works just fine except it cannot write into any file and 'flask_for_test.py' works perfectly.
I don't know whether the format of the file name has an effect on the function of python but using lowercase file name works for me.
By the way, all other solutions I found didn't work.

Can't import local module inside script, like I do in Django shell

This is the error:
Traceback (most recent call last):
File "twitterstream.py", line 3, in <module>
from tweemo.models import TwitterStream
ImportError: No module named tweemo.models
Background:
In Django I have a simple model which looks like so:
from django.db import models
class TwitterStream(models.Model):
text = models.CharField()
From inside the Django shell I can do the following without problems
>>> from tweemo.models import TwitterStream
>>> tweet = TwitterStream.objects.create(text = 'hello again')
>>> tweet.text
'hello again'
Because this worked in the django shell, I thought I could insert this line:
>>> from tweemo.models import TwitterStream
into any regular python script and, for example, insert the data into the TwitterStream Model (and thus my into my Mondo Database) form within the script.
Basically, I have a script which does print out the twitter live stream onto the command line. Itried to modify it by including this
>>> from tweemo.models import TwitterStream
and changing this:
for line in response:
print response
into this:
for line in response:
tweet = str(tweet) + str(" ") + str(count)
tweet = TwitterStream.objects.create(text = line.strip())
count += 1
FYI: My models.py containing the TwitterStream class is inside my app 'tweemo' which is inside a project, also called 'twitter'. The python script I want to send the live stream into mymongo DB with, is in the same folder as the models.py file -the tweemo app folder.
I'm new to Django/Mongo so Imight be way off here..
Thanks in advance
Python will automatically check for modules in the same directory as the input script, so you can just write
from models import TwitterStream
This behaviour is different when you are in the django shell, as django appends the project root path to sys.path, which Python also uses when searching for modules.
if importing of model works via django shell it has to work via py files within project folder.
My only guess would be to delete pyc file in project folder and test.If not, #dannymilsom solution will come in handy :)

Categories