Posts Tagged ‘ASE’
So following on from a comment to my previous post about Android Scripting Environment with Python, I thought I should update the original Google Analytics script with some of the new shiny that ASE provides.
I downloaded ase_r20.apk from the ASE website to take advantage of some of the new features.
One of the nice things is that you can now quickly input code via the API Browser menu option, which gives you a great list of all the API calls that ASE supports. It certainly helps reduce the errors and speed up the development time … especially when you’re typing on the Android’s virtual keyboard.
One thing which I’ve wanted to do for a long time is improve the dialog display and give some feedback to the user that something is indeed happening whilst the script goes off to talk to Google Analytics.
Fortunately, ASE now provides some dialog related API calls, including two types of progress indicators — an indeterminate circular spinner, and a traditional horizontal progress bar.
Amending the code is easy enough. Pop open the script in the editor, scroll down a few lines, select API Browser from the menu options, select dialogCreateSpinnerProgress, add some helpful text to the dialog box, select dialogShow again from the API Browser, and ta-da; you have an indicator to the user that something is happening. When the lengthy process is finished, you simply call dialogDismiss to remove the progress indicator.
Also, I used a bit of a hack to get the display of the final data last time, and I wanted to improve on this, because if you have a lot of data, the end of the dialog box gets pushed off the screen and the “Ok” button gets truncated too.
Again, ASE has a new dialogCreate API call. Inserting this into the code, followed by a dialogSetPositiveButtonText to create an “Ok” button is all you need. The dialog is dismissed automatically when you press the button.
Nice and simple, eh?
So, our final code would look something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | """ Google Android Python Development example, using the Android Scripting Language (ASE). This is an example of how to communicate with the Google Analytics Data API via Python. Author: Howard Sandford, April 2010 Released under CC BY-SA-NC 3.0 """ import gdata.analytics.service import datetime import android # For use with the ASE droid = android.Android() # Let the user know we're doing something droid.dialogCreateSpinnerProgress('Please wait ...', 'Collecting Google Analytics data', 100, False) droid.dialogShow() # The Google Analytics account login details USERNAME = 'your_email_account@gmail' PASSWORD = 'your_password' # We want data for the last 7 days end_date = datetime.datetime.today().strftime('%Y-%m-%d') start_date = (datetime.datetime.today() - datetime.timedelta(7)).strftime('%Y-%m-%d') # Authenticate ourselves against the Analytics Data API client = gdata.analytics.service.AnalyticsDataService() client.ClientLogin(USERNAME, PASSWORD) # Grab the data for a particular profile_id -- in this case the # number of visits for the keywords that people have searched for us data = client.GetData( ids='ga:123456', dimensions='ga:keyword', metrics='ga:visits', sort='-ga:visits', start_date=start_date, end_date=end_date, ) # print out the results total_visits = 0 analytics_results = [] for entry in data.entry: analytics_results.append('%s visits for %s\n' % (entry.metric[0].value, entry.dimension[0].value)) total_visits = total_visits + int(entry.metric[0].value) analytics_results.append('-----\n') analytics_results.append('Total of %s visits between %s and %s\n' % (total_visits, start_date, end_date)) # Ok, we're ready to show our results, so stop the progress indicator droid.dialogDismiss() # Now show the results to the user droid.dialogCreateAlert('Analytics Data', ''.join(analytics_results)) # Add an OK button to our dialog droid.dialogSetPositiveButtonText(' Ok ') droid.dialogShow() # Finish! droid.exit() |
Feel free to play around with this code, obviously putting in your own values for username, password and Google Analytics web-site profile id. In the meantime, I’ll work on a few more examples showing some of the other useful user interface API calls.
[All files are released under Creative Commons BY-SA-NC 3.0]
Over the holiday period, Sarah and I went visiting at her mum’s in Ipswich. Now, I’m not saying that they lack technology down there or anything, but there was no internet connection. None whatsoever. Zilch. Nada. Eeek!
What’s a techie guy meant to do in that situation? I didn’t have a laptop or notebook with me, so I had to make do with my Android phone as the only source of technological entertainment and sole connection into the real world
Now, I’d heard about the Damon Kohler’s ASE (Android Scripting Environment) quite a while back, but never really got round to looking at it or taking it for a spin. I’ve developed a few apps using the Android SDK, and even though Java isn’t my primary language, the whole platform has been designed to make it easy for developers to get their apps working really quickly.
However, day-to-day at Linden Lab, I work primarily in Python, so this looked like the perfect opportunity to have a delve into Python scripting use ASE, and it suited my circumstances perfectly — after all, you can type directly into the Android terminal and edit your Python scripts there and then without having to be tethered to a computer.
Installing ASE was a breeze directly from the web-site, and the supported environments were easy to install from within ASE itself — you can develop in Lua, JavaScript, Ruby, BeanShell, or Perl; Python was my choice though, obviously. So, following the instructions, getting started was really quick. There are some example scripts to get you going, including a test script which quickly runs through some of the features.
And then I saw it:
import gdata.docs.service
Oooh. Nice. I was going to install the Google Data API Python libraries and have a play with those, and fortunately for me all the Google Data API Python modules were included in the standard ASE install. Yay! In fact, you have everything you need to talk to all of Google’s APIs — Google Docs, Base, Blogger, Calendar, Contacts, YouTube, Webmaster Tools, Maps … they’re all there!
I was thinking of having a script that could check the stats on my web-site via Google Analytics. I know I could have just browsed to the stats pages using Android’s built in browser, but where’s the fun in that
Now I can use the Google Analytics API to directly query the stats via a Python script running on my Android.
I’ve done quite a bit of work with Google Adwords APIs, but nothing in Python, but reading through the Analytics API documentation gave enough direction. Essentially you need to authenticate yourself with the service you’re after, then make a query against the data with the parameters you want to filter on. Seriously, it’s that simple.
Of course, it being a small soft keyboard, it took a day and an age to type in the Python code. Fortunately for me, I had a lot of time to kill, and this was the closest I was going to get to any kind of computing power for a few days! Get those fat fingers typing on that diddy screen …
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | """ Google Android Python Development example, using the Android Scripting Language (ASE). This is an example of how to communicate with the Google Analytics Data API via Python. Author: Howard Sandford, December 2009 Released under CC BY-SA-NC 3.0 """ import gdata.analytics.service import datetime import android # For use with the ASE droid = android.Android() # The Google Analytics account login details USERNAME = 'your_email_account@gmail' PASSWORD = 'your_password' # We want data for the last 7 days end_date = datetime.datetime.today().strftime('%Y-%m-%d') start_date = (datetime.datetime.today() - datetime.timedelta(7)).strftime('%Y-%m-%d') # Authenticate ourselves against the Analytics Data API client = gdata.analytics.service.AnalyticsDataService() client.ClientLogin(USERNAME, PASSWORD) # Grab the data for a particular profile_id -- in this case the # number of visits for the keywords that people have searched for us data = client.GetData( ids='ga:123456', dimensions='ga:keyword', metrics='ga:visits', sort='-ga:visits', start_date=start_date, end_date=end_date, ) # print out the results total_visits = 0 analytics_results = [] for entry in data.entry: analytics_results.append('%s visits for %s\n' % (entry.metric[0].value, entry.dimension[0].value)) total_visits = total_visits + int(entry.metric[0].value) analytics_results.append('-----\n') analytics_results.append('Total of %s visits between %s and %s\n' % (total_visits, start_date, end_date)) #droid.makeToast(''.join(visits_list)) droid.getInput('Analytics Data', ''.join(analytics_results)) |
Seriously, that’s how easy it is to work with the Analytics API.
The USERNAME and PASSWORD are the same as the email address and password that you would use to log into your Adwords/Analytics dashboard on the web. And no, strangely enough, what you see in the above code is not my username/password
In the code, the following snippet warrants a little more explanation:
29 30 31 32 33 34 35 36 | data = client.GetData( ids='ga:123456', dimensions='ga:keyword', metrics='ga:visits', sort='-ga:visits', start_date=start_date, end_date=end_date, ) |
The ids, here set to ga:123456, is the profile id(s) of the web-site(s) you want to retrieve details of (and no, ga:123456 is not my profile id either!). Profile id is also referred to as tableId in the Google Analytics API. You can find your profile id easily enough by logging into your Adwords/Analytics account and then selecting edit on the profile. As you can see in the screenshot below, the profile id is clearly displayed. The profile id is a number, and you just need to add the ‘ga:’ in front of it.

The dimensions parameter describes how you want your data categorised; the metrics parameter describes what details you actually want to see. In my script, I wanted to see the number of visits to this web-site split by what keyword the visitor used to find the site. The sort parameter above shows that I wanted the results displayed in descending order of visits, i.e. the highest number of visits first.
The start_date and end_date parameters speak for themselves.
The values for dimensions and metrics could contain more than one item, separated by commas, and the full list of available dimensions and metrics can be found in the Google Analytics Dimensions and Metrics reference.
I originally used droid.makeToast() to pop-up the results on the screen, but the pop-up didn’t stay on the screen long enough for me to read all the returned information! The original Java implementation allows you to change the time it shows on the screen, but ASE’s makeToast() doesn’t have that parameter available. So instead I’ve used droid.getInput() to display the Google Analytics data.

This method, as the name suggests, is usually used to get input from the user, however I found that using it provides a convenient way to display the data in a modal dialog, complete with OK button and scroll-bars if necessary. ASE doesn’t yet provide any other dialog capabilities — or in Android SDK speak, intents — and no other GUI design is available. If I were to extend this mini-app, I would prefer a more esoteric display, but if I’m going to do that it would be easier to develop the whole thing in Java from scratch … hrm, perhaps an idea for another project …
… and remember, the main reason for starting this scripting endeavour was because I didn’t have any computer available to develop on, and so Python via ASE was the perfect way to achieve my goal.
So there you have it, a simple Google Analytics Python script on the Google Android using ASE (Android Scripting Environment). If you have questsions, just let me know!
[Edit: I've added a follow-on update to improve the user interface using the latest ASE Python Android Scripting Environment here]
[All files are released under Creative Commons BY-SA-NC 3.0]