33'''PageSpeed Insights Single + Google Cloud Functions'''
44import os
55import base64
6+ import json
7+ from urllib import parse
68import requests
9+ from google .cloud import storage
10+ from google .cloud .storage import Blob
711
812# Access Token, generated from GCP Console Credentials page.
913API_KEY = os .getenv ('GCP_API_KEY' )
1519PROXIES = None
1620
1721
22+ def save (url , report ):
23+ '''Save to https://console.cloud.google.com/storage/browser/[bucket-id]/'''
24+ client = storage .Client ()
25+ bucket = client .get_bucket ("psi-report" )
26+ blob = Blob (f"${ parse .quote_plus (url )} .json" , bucket )
27+ blob .upload_from_string (report , "application/json" )
28+
29+
1830def run (url ):
1931 try :
2032 payload = {"url" : url ,
@@ -25,7 +37,8 @@ def run(url):
2537 }
2638 response = SESSION .get (url = GAPI_PSI , params = payload , proxies = PROXIES )
2739 print (response .status_code )
28- print (response .json ())
40+ if 200 == response .status_code :
41+ save (url , response .text )
2942 except requests .RequestException as _e :
3043 print (_e )
3144 return 'OK'
@@ -47,25 +60,11 @@ def test_run_pubsub(test_url):
4760
4861
4962if __name__ == "__main__" :
63+ _proxy = os .getenv ("HTTP_PROXY" )
5064 PROXIES = {
51- "http" : "127.0.0.1:1087" ,
52- "https" : "127.0.0.1:1087" ,
65+ "http" : _proxy ,
66+ "https" : _proxy ,
5367 }
54-
5568 _test_url = "https://m.ctrip.com/webapp/flight/schedule/detail.html"
5669 test_run_http (_test_url )
5770 test_run_pubsub (_test_url )
58-
59-
60- """
61- from google.cloud import storage
62- client = storage.Client()
63- # https://console.cloud.google.com/storage/browser/[bucket-id]/
64- bucket = client.get_bucket('bucket-id-here')
65- # Then do other things...
66- blob = bucket.get_blob('remote/path/to/file.txt')
67- print(blob.download_as_string())
68- blob.upload_from_string('New contents!')
69- blob2 = bucket.blob('remote/path/storage.txt')
70- blob2.upload_from_filename(filename='/local/path.txt')
71- """
0 commit comments