Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Thursday, July 13, 2017

Download Sentry Events via RESTful API

For those users who use Sentry as a error recording service. When you got an error issue, and wanting to know all events detail. But on Sentry web interface, you can read an event each time. And, of course, you wouldn't like the idea of copying each event til it ends. Fortunately, Sentry provided a web API for users who analysis data on their Sentry server. You may refer to Sentry API Docs for more detail.

After some time to explore, I understand that you need to create an access token on your sentry server http://your-host/api/. And after you are done, you are ready to access the APIs listed on the above document. And here is a simple example I used to retrieve all events of an issue and make some analysis.

import json, re, requests, sys

def main(host, issueId, token):
  endpoint = "http://%s/api/0/issues/%s/events/" % (host, issueId)
  headers = {"Authorization": "Bearer " + token}
  with open("data/%s.json" % issueId, "w") as f:
    f.write("[")
    nextLink = endpoint
    while (nextLink != None):
      if nextLink != endpoint :
        f.write(",")
      response = requests.get(nextLink, headers=headers)
      text = response.text[1:-1]
      f.write(text)
      headerLink = response.headers.get("link", "")
      regSearch = re.search("<([^<]*)>; rel=\"next\"; results=\"(true|false)\";", headerLink)
      if len(regSearch.groups()) >= 2 and regSearch.group(2) == "true":
        nextLink = regSearch.group(1)
      else:
        nextLink = None
    f.write("]")

In the above code, I uses Python requests to send requests to the sentry server. And I apply the regular expression to extract the next link of this page. I guess this shall be a simple one, and now you are ready to get your hands on the massive error logs.

Thursday, July 6, 2017

Retrieve Access(Bearer) Token via oauth2client

I am doing a project interfacing with Google Cloud Platform and service account. But this time, I am not going to access the service with personal account, I do not want user experience the authentication window, and the personal profile doesn't matter. Then I found there was a kind of credential called service account, that I can make all users access the service with this account.

Besides that, I don't want create a credential file on users device. So I need a lite-weight authentication. And fortunately, there is a kind of stuff called access token, which generated by the service account key file(which suppose to be a secret). With the access token, you can access the service via a simple request associated with a bearer token.

After all these survey, I am going to find a way to generate the access token automatically. Initially, I knew that gcloud could generate token via gcloud auth activate-service-account then gcloud auth print-access-token, but I don't want to make the application make system call if not necessary. And it took me quite some time and effort to learn how to do that. I find myself got poor knowledge about OAuth2, so I downloaded the gcloud source code via from google-cloud-sdk. (I just read the gcloud installation bash and found this link.)

And I found the concept of OAuth2 service account authentication pretty intuitive. All you need to do is read the key file which you obtained from Google Developer Console, and refresh the service account credential. The following is an illustration:

from oauth2client.service_account import ServiceAccountCredentials
import httplib2

fileName = "/path/to/your/service-account-secret.json"
creds = ServiceAccountCredentials.from_json_keyfile_name(
  fileName,
  scopes=['https://www.googleapis.com/auth/cloud-platform'])
creds.user_agent = creds._user_agent = "google-cloud-sdk"
# User agent may not be necessary.
# This suffered from oauth2client bug, so we have to assign it manually.
# See https://github.com/google/oauth2client/issues/445
creds.refresh(httplib.Http())
print(creds.access_token)

Since the snippet is from gcloud, it inherits some knowledge from Google. The Credential object suffering a bug about _user_agent. so we need to assign the user_agent manually.

And with the access token generating script, I could deploy a micro-service for authenticating usage. If users needed an access token, I just refresh the credential and respond the token to users. And don't forget, the token is valid for one hour, so you may apply some micro-cache mechanism(like nginx provided) to your application and reduce the server loading.

Saturday, August 6, 2016

MSQLdb/SQLAlchemy Python Streaming

  When you are dealing with huge query result from sql server(let's say, about 30k rows), your program may consume a lot of memory to collect the result. In such a case, you probably want to retrieve the result by streaming. This article shows how to enable the streaming feature with python.

  If you are using MySQLdb, the drill is simple. You just instantiate your cursor with SSCursor, and boom, this cursor serve you as a server-side streaming cursor. The following snippet is a demonstration.
import MySQLdb.cursors
import MySQLdb

conn = MySQLdb.connect(host=host, user=user, passwd=password, db=db)
cursor = SSCursor(conn)
query = "SELECT * FROM big_table;"
cursor.execute(query);
# rowcount wouldn't work here


  For those projects using SQLAlchemy, you may have tried conn.execution_options(stream_results=True) and fruitless, it still consumes a lot of memory. Since the flag doesn't work with MySQL.
  Cheers, Love! The Cavalry's Here! There is another solution there, since SQLAlchemy is based on MySQLdb, they have actually provided a way to inject the SSCrusor. Here is an example.
import sqlalchemy
import MySQLdb.cursors
CHUNK_SIZE = 10000

url = "mysql://%s:%s@%s:%d/%s" % (user, password, host, port, db)
query = "SELECT * FROM big_table;"
conn = sqla.create_engine(url, encoding="utf-8",
  connect_args={"cursorclass": MySQLdb.cursors.SSCursor})
cursor = conn.execute(query)

rows = cursor.fetchmany(CHUNK_SIZE)
while(len(rows) > 0):
  # do whatever it is you do to the data
  rows = cursor.fetchmany(CHUNK_SIZE)
  Of course, you would like to read the streaming result as some chunks, so the overwhelming rows number wouldn't cause a network transferring bottleneck.

  Another thing to mention. While enabling the streaming feature, rowcount wouldn't work. Probably because the results are stored in server-side, it's impossible to read how many rows it actually be.

Saturday, March 12, 2016

Interface to Google APIs with Python

    I have demonstrated how to obtain a Google App credential of a user in the last post. And of course, you read that post because you need to create an application. This post is talking about how to use Google-API-Python-Client and its interface concept idea(of course, under my own interpretation). I will mainly use Drive API in this demonstration.



    To call Google services you need to import the following packages:
import apiclient
from oauth2client.file import Storage
import httplib2


    Before you calling a service API, you need to retrieve corresponding service with the user credential obtained by previous post. Like the following:
SERVICE_NAME = 'drive'
SERVICE_VERSION = 'v3'
storage = Storage(CREDENTIAL_NAME)
credential = storage.get()
http = credential.authorize(httplib2.Http())
service = apiclient.discovery.build(SERVICE_NAME, SERVICE_VERSION, http=http)

    The SERVICE_NAME is which service you are going to retrieve, and SERVICE_VERSION is the service, obviously. The services names and versions can be seen on APIs-Explorer. You can easily click the service you want to interface, and check the prefix before first .(dot) of each API. The same service suppose to have the same prefix, that is your service name. And the version just depends on your need, it shall be in the form v[1-9].

    Now you have retrieved the service instance, let's see which API you are going to call. At the previous section, you have decide the service name with first term of API name. You are going to check what the remaining terms are, that is the path to make the API call. For example, when you are calling drive.files.list it maps to Python code service.files().list(...); or analytics.data.ga.get corresponds to service.data().ga().get(...)(Of course, the service are retrieve by different build() call.)

    And you are giving the parameters of an API with the Pythonic named arguments. The following is a call of drive.files.list:
PAGE_SIZE = 10
QUERY = "name contains 'Hello'"
FIELDS = 'nextPageToken,files(id, name)'
service.files().list(

pageSize=PAGE_SIZE,
q=QUERY,
fields=FIELDS
)

    According the document of drive.files.list, we can simply assign the parameters with named arguments.

    However, it is not always as simple as the above. Like the API drive.files.create, you cannot specify the upload content in parameters shown in reference. In this case, I recommend you to check your API with Interactive Help in IPython(or pure Python interpreter). Like the following:
help(service.files().create)
    With help(...), you are able to check all information about this function, including arguments and returned value in a very detailed way.

    After checked the drive.files.create with help(...), now we are able to make file upload(creation). Like the following:
FILE_NAME = "test_text"
mediaBody = apiclient.http.MediaFileUpload(FILE_PATH, mimetype='text/plain')
body = {
"name": FILE_NAME
}
service.files().create(media_body=mediaBody, body=body)
# or the following
# service.files().create(media_body=mediaBody, name=FILE_NAME)




    This is it. When I was interfacing Google APIs, I have encountered a lot problems and did a lot of googling. The above all was my notes about the package. Help it is helpful for you.

Monday, February 29, 2016

Generate Google Application User Credentials with Python/Flask

    Recently, I got a demand of building Google Application for our company. After some trials, I understood how things work. And I want to document it, hope it is going to help people who met a similar need.

    First of all, you need to create a project for your application on Google Develops Console. And then you need to enable the service you are going to interface, by click the link 'Enable and manage APIs' or enter the 'API Manager.' Now you are suppose to see a few lists of Google APIs, choose the one that you need, and click the enable button.

    The following step is to generate application credentials. Go to the 'API Manager > Credentials,' and click Create Credentials > API key. You are going to select between types 'Server key', 'Browser key', 'iOS key' or 'Android key', this depends on which platform your application is(Here I choose the server key, because my application is going to call APIs on a server instead of browsers or mobiles.) All information you need to provide for this key is server name(If you can provide your server IP address is better, of course.)  Now you can see you API key in the credentials page.

    After you generated an API key, there are another credential to generate. Which is OAuth 2.0 Client ID. Before you click the 'create credentials' button, you need to switch to the tab 'OAuth consent screen' which is just above the 'create credentials' button and fill the field 'Product name shown to users'. Now you are fine to create the 'OAuth client ID' by clicking 'create credentials'. You need to choose which type of your application type(I guess this doesn't really matter, I choose the 'Other' type), and fill your application name. After you created the client ID, you are able to download your client key in the credentials page, the right side of your client ID. And your client secret are able to be seen by click your client ID name.

** Remember, anyone of API keys, client IDs and client secret are suppose to be kept secret. DO NOT share with anyone which is not in your project. **

    Now you are done with all the paperworks, let's get hands dirty. You need to get user credentials to perform actions for this user. I deploy an web application to acquire user credentials with Python/Flask. You need to build two pages, one is for requesting authentications, the other one is for retrieve authentications. The application may like this
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.file import Storage

from flask import Flask, url_for, redirect, request
app = Flask(__name__)

CLIENT_ID_FILE = "your_client_id_file_name"
CLIENT_SECRET = "your_client_secret"
SCHEME = "http://"
DOMAIN = "localhost:5000"
AUTH_RETURN_PATH = "/auth_return"
REDIRECT_URI = SCHEME + DOMAIN + AUTH_RETURN_PATH
CREDENTIAL_NAME = "credential_name"
SCOPES = [
  "https://www.googleapis.com/auth/drive.file"
]

@app.route("/auth")
def auth():
  storage = Storage(CREDENTIAL_NAME)
  credentials = storage.get()
  if not credentials or credentials.invalid:
    print("!!! Cannot find this credential !!!")
    return request_credential(storage)
  else:
    return "Your have authorized your credential."

def request_credential(storage):
  flow = OAuth2WebServerFlow(client_id=CLIENT_ID_FILE,
    client_secret=CLIENT_SECRET,
    scope=SCOPES,
    redirect_uri=REDIRECT_URI)
  auth_uri = flow.step1_get_authorize_url()
  return redirect(auth_uri)

@app.route("/auth_return")
def auth_return():
  flow = OAuth2WebServerFlow(client_id=CLIENT_ID_FILE,
    client_secret=CLIENT_SECRET,
    scope=SCOPES,
    redirect_uri=REDIRECT_URI)
  credentials = flow.step2_exchange(request.args.get("code", ""))
  storage = Storage(CREDENTIAL_NAME)
  storage.put(credentials)
  credentials = storage.get()
  if not credentials or credentials.invalid:
    return "Authorization failed."
  else:
  return "Authorization succeed."


    In the above codes, the entry point is 'http://localhost:5000/auth', which would lead user to auth(). It check if the credential exists, it call the request_credential if not. The authentication is following OAuth 2.0 two-step authentication, so it will lead user to Google to authenticate his/her authentication and then redirect to the return path that you have given in redirect_uri.

    After you got the credential and call storage.put(credential), the credential will be stored at the location CREDENTIAL_NAME(Absolute or relative path depends on it.)

    There is a constant named CLIENT_ID_FILE, which is the path to your client ID in your file system, however, without the extension(.json). And obviously, CLIENT_SECRET is what have been mentioned in the above article.

    And the SCOPES in the code, can be found in the API document. In this example, I requested the https://www.googleapis.com/auth/drive.file scope, which is shown in the Drive document.



    After you read this article, you should be able to get a Google service credential from a user. If there is any part is unclear, please ask without hesitation, I am glad to answer it. I may write another post for how to operate some Google services that I have interfaced with.

Monday, January 18, 2016

Setup WebHDFS on Existed Hadoop and Operate with Python

This article is based on how to enable the WebHDFS on Hadoop and then read/write with Python. If you haven't setup a Hadoop environment, I recommend you follow this tutorial.

Recently, I need to setup and test Hadoop on work. And I find the instruction on Hadoop is not detailed enough. However, after some googling, I finally done the setup and test. Here are some experiences, hope it would be helpful. :)



1. Enable the WebHDFS in the configuration file,
"HADOOP_HOME/etc/hadoop/hdfs-site.xml"
By inserting:
<property>
   <name>dfs.webhdfs.enabled</name>
   <value>True</value>
</property>
And restart the Hadoop server. After that, the WebHDFS shall be ready for Hadoop web API. In this article, I will not cover the authenticated WebHDFS operation.

2. Test the service with curl.
i. Create
For create a file via WebHDFS, you can execute the command
curl -i -X PUT "http://<HOST>:<PORT>/webhdfs/v1/<PATH>?op=CREATE"
And you will receive a HTTP 307 which bring you a location to where to create file.
Then execute the following
curl -i -X PUT -T <LOCAL_FILE> <LOCATION_FROM_PREVIOUS>
The above one only allow you to upload a file. If you want to send string to the file, just replace the "-T <LOCAL_FILE>" to "-d <DATA>"
ii. Read
then you can read file with
curl -i -L "http://<HOST>:<PORT>/webhdfs/v1/<PATH>?op=OPEN"
Reading API also apply the two-step operation strategy. In this part, you just follow the returned location then you can get the data/file you are indexing.
Now, if you have successfully setup the WebHDFS, you will see that it create and return your file correctly. If you want to learn more about operations to WebHDFS with curl. Please refer the official instruction.

3. Operations with Python/hdfs [doc]
i. Install this package
pip install hdfs
ii. Write a configuration file
[global]
default.alias = dev

[dev.alias]
url = http://hdfs.hashfarm.cc:50070
user = sunshire
This config file is telling mtth/hdfs to connect to http://hdfs.hashfarm.cc:50070 as sunshire when the alias is dev, also set 'dev' as the default alias.
And the file shall be saved at ~/.hdfscli.cfg by default. Or you can set the environment variable HDFSCLI_CONFIG to specify your very own config file location.
iii. Write yourself a script
from hdfs import Config
import sys
fileName = "/helloWord"
message = "Hello :)"

client = Config().get_client()

with client.write(fileName, overwrite=True) as writer:
  writer.write(message)

ls = client.list("/")
if fileName not in ls:
  print("file not found")
  sys.exit()

readMessage = ""
with client.read(fileName) as reader:
  readMessage = reader.read()

print("wrote: " + message + ", read: " + readMessage)
In the above code, we generate a client via config. Here it apply the default alias, which is 'dev'. To claim a explicit alias just pass the alias to the first parameter to get_client, like the following:
client = Config().get_client("dev")
With mtth/hdfs, you can read/write hdfs like ordinary python file operations, just using the with syntax.
By using client.list, you can get the sub-directory list of a directory.
Notice, while indexing a file or a directory. Remember to add "/" at the beginning. Otherwise the package will not find a corresponded path, and do not throw an error, either.