예제 #1
0
    def handle(self, *args, **options):
        if len(args) < 2:
            raise CommandError("Not enough arguments")
        org = args[0]
        client_secret_path = args[1]

        # Fail early if the university does not exist
        university = University.objects.get(code=org)

        # is the file a client-secret file or a credentials file?
        with open(client_secret_path) as f:
            json_data = f.read()
            file_data = json.loads(json_data)
            if "scopes" in file_data:
                self.stdout.write("Importing access token...")
                credentials = GoogleCredentials.from_json(json_data)
            else:
                self.stdout.write("Start flow from client secrets...")
                credentials = flow_from_client_secrets(client_secret_path)

        # Save credentials to database
        YoutubeAuth.objects.create(
            university=university,
            client_id=credentials.client_id,
            client_secret=credentials.client_secret,
            access_token=credentials.access_token,
            refresh_token=credentials.refresh_token,
            token_expiry=credentials.token_expiry,
        )
        self.stdout.write("Youtube auth token created")
예제 #2
0
    def authenticate(self,
                     auth_scopes: List[str] = _AUTH_SCOPES,
                     credentials_file: str = '.google_fit_credentials'):
        """
        Authenticate and give access to google auth scopes. If no valid credentials file is found, a browser will open
        requesting access.
        :param auth_scopes: [optional] google auth scopes: https://developers.google.com/identity/protocols/googlescopes#fitnessv1
        :param credentials_file: [optional] path to credentials file
        """
        #flow = OAuth2WebServerFlow(self._client_id, self._client_secret, auth_scopes)
        #storage = Storage(credentials_file)
        #credentials = storage.get()

        #s3 = boto3.resource('s3')
        #content_object = s3.Object(os.environ['s3_bucket'], os.environ['key'])
        #file_content = content_object.get()['Body'].read().decode('utf-8')
        #json_content = json.loads(file_content)
        #credentials=json_content

        #s3 = boto3.client('s3',aws_access_key_id=os.environ['AWS_ACCESS_KEY_ID'],aws_secret_access_key=os.environ['AWS_SECRET_ACCESS_KEY'])
        #response = s3.get_object(Bucket=os.environ['s3_bucket'], Key=os.environ['key'])
        credentials_json = os.environ['google_credentials']
        credentials = GoogleCredentials.from_json(credentials_json)
        if credentials is None or credentials.invalid:
            credentials = tools.run_flow(flow, storage)
        http = httplib2.Http()
        http = credentials.authorize(http)
        self._service = build('fitness', 'v1', http=http)
예제 #3
0
def query_google_ocr(image_content):
    '''Run a label request on a single image'''

    API_DISCOVERY_FILE = 'https://vision.googleapis.com/$discovery/rest?version=v1'
    http = httplib2.Http()
    creds_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                              'google_credentials.json')
    with open(creds_path) as f:
        creds_json = f.read()

    credentials = GoogleCredentials.from_json(creds_json).create_scoped(
        ['https://www.googleapis.com/auth/cloud-platform'])

    credentials.authorize(http)

    request_body = {
        'requests': [{
            'image': {
                'content': image_content
            },
            'features': [{
                'type': 'TEXT_DETECTION',
                'maxResults': 1
            }]
        }]
    }

    version = 'v1'

    cache_prefix = 'google/vision/%s' % version
    request_body_blob = json.dumps(request_body).encode('utf8')

    response_json = cache.get(cache_prefix, request_body_blob)

    if response_json:
        return json.loads(response_json.decode('utf8'))

    service = build('vision',
                    version,
                    http=http,
                    discoveryServiceUrl=API_DISCOVERY_FILE)
    service_request = service.images().annotate(body=request_body)

    responses = service_request.execute()['responses']

    if 'error' in responses[0]:
        raise Exception("Received error from Google: %s" %
                        responses[0]['error'])

    cache.put(cache_prefix, request_body_blob,
              json.dumps(responses).encode('utf8'))

    return responses
예제 #4
0
def query_google_ocr(image_content):
  '''Run a label request on a single image'''

  API_DISCOVERY_FILE = 'https://vision.googleapis.com/$discovery/rest?version=v1'
  http = httplib2.Http()
  creds_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'google_credentials.json')
  with open(creds_path) as f:
      creds_json = f.read()

  credentials = GoogleCredentials.from_json(creds_json).create_scoped(
      ['https://www.googleapis.com/auth/cloud-platform'])


  credentials.authorize(http)

  request_body = {
      'requests': [{
        'image': {
          'content': image_content
         },
        'features': [{
          'type': 'TEXT_DETECTION',
          'maxResults': 1
         }]
       }]
    }

  version = 'v1'

  cache_prefix = 'google/vision/%s' % version
  request_body_blob = json.dumps(request_body).encode('utf8')

  response_json = cache.get(cache_prefix, request_body_blob)

  if response_json:
    return json.loads(response_json.decode('utf8'))

  service = build('vision', version, http=http, discoveryServiceUrl=API_DISCOVERY_FILE)
  service_request = service.images().annotate(body=request_body)


  responses = service_request.execute()['responses']


  if 'error' in responses[0]:
      raise Exception("Received error from Google: %s" % responses[0]['error'])

  cache.put(cache_prefix, request_body_blob, json.dumps(responses).encode('utf8'))

  return responses
예제 #5
0
def update_feed(feed):
    profile_string = feed.profile
    calendar_id = feed.calendar_id
    creds = GoogleCredentials.from_json(profile_string)
    service = build_service(creds)

    events = service.events().list(calendarId=calendar_id,
                                   updatedMin=feed.last_updated).execute()

    print(feed.id)
    for event in events["items"]:
        feed.events.create(
            name=event["summary"],
            event_feed_id=event["id"],
            start=event["start"]["dateTime"],
            end=event["end"]["dateTime"],
            location=event["location"] if "location" in event else "",
            description=event["description"] if "description" in event else "")

    feed.last_updated = datetime.now().isoformat() + "Z"
    feed.save()