AttributeError: 'dict' object has no attribute 'Credentials' - flask

I'm trying to use a service account directly from a python script with the need to have a json file path that contains the service account but I keep running into this error, btw I'm trying to run my code via a flask app.
Here is the flask app:
from flask import Flask, request, jsonify, render_template
# from google.cloud import bigquery
# from google.oauth2 import service_account
import json
# import os
import pandas as pd
# Create the app object
app = Flask(__name__)
# importing function for calculations
from Record_Matching import Matching
#app.route("/query", methods = ['get'])
def query():
params = request.json
# query1 = request.args.get('query1', type = str)
# query2 = request.args.get('query2', type = str)
# querycolumns = request.args.get('querycolumns')
# project_id = request.args.get('project_id', type = str)
# service_account = request.args.get('service_account')
# SS = request.args.get('SS', type = float)
# TT = request.args.get('TT', type = float)
result = Matching(params['query1'],params['query2'], params['SS'],params['TT'], params['service_account'], params['project_id'], params['querycolumns'])
return result
if __name__ == "__main__":
app.run(host="localhost", port=8080, debug=True)
this is my function source:
import pandas as pd
from google.cloud import bigquery
from google.oauth2 import service_account
# from google.cloud.bigquery.client import Client
import recordlinkage
from recordlinkage.preprocessing import phonetic
import uuid
from uuid import uuid4
import random
import string
import json
import os
# Results to data frame function
def gcp2df(sql, client):
query = client.query(sql)
results = query.result()
return results.to_dataframe()
# Exporting df to bigquery - table parameter example: "dataset.tablename"
# def insert(df, table):
# client = bigquery.Client()
# job_config = bigquery.LoadJobConfig(write_disposition=bigquery.job.WriteDisposition.WRITE_TRUNCATE)
# return client.load_table_from_dataframe(df, table, job_config = job_config)
def pair(df1, df2, TT, querycolumns):
# function to take pair from list and compare:
L = querycolumns
l=len(querycolumns)
p1=0
p2=1
# To generate phonetics we need to make sure all names are in english.
# thus we'll replace non-english words by random english strings
df1[L[p1]] = df1[L[p1]].astype(str)
df2[L[p2]] = df2[L[p2]].astype(str)
for i in range(0,len(df1)):
if df1[L[p1]][i].isascii() == False:
df1[L[p1]][i] = ''.join(random.choices(string.ascii_lowercase, k=5))
for i in range(0,len(df2)):
if df2[L[p2]][i].isascii() == False:
df2[L[p2]][i] = ''.join(random.choices(string.ascii_lowercase, k=5))
compare = recordlinkage.Compare()
df1["phonetic_given_name"] = phonetic(df1[L[p1]], "soundex")
df2["phonetic_given_name"] = phonetic(df2[L[p2]], "soundex")
df1["initials"] = (df1[L[p1]].str[0] + df1[L[p1]].str[-1])
df2["initials"] = (df2[L[p2]].str[0] + df2[L[p2]].str[-1])
indexer = recordlinkage.Index()
indexer.block('initials')
candidate_links = indexer.index(df1, df2)
compare.exact('phonetic_given_name', 'phonetic_given_name', label="phonetic_given_name")
# O(n) a function that uses two pointers to track consecutive pairs for the input list
while p2 <=l:
compare.string(L[p1], L[p2], method='jarowinkler',threshold = TT, label=L[p1])
p1+=2
p2+=2
features = compare.compute(candidate_links,df1, df2)
return features
def Matching(query1,query2, SS,TT, service_account, project_id, querycolumns):
# Connections
# with open('service_account.json', "w") as outfile:
# json.dump(service_account, outfile)
job_config = bigquery.LoadJobConfig()
credentials = service_account.Credentials.from_service_account_info(service_account)
client = bigquery.Client(credentials = credentials, project = service_account['project_id'])
# client = bigquery.Client(project= project_id)
# os.environ["GOOGLE_APPLICATION_CREDENTIALS"]= 'service_account.json'
# if os.path.exists("service_account.json"):
# os.remove("service_account.json")
# client = Client.from_service_account_json('service_account.json', project=project_id)
# credentials = service_account.Credentials.from_service_account_file('service_account.json')
# client = bigquery.Client(credentials=credentials, project=credentials.project_id,)
SS=int(SS)
TT=float(TT)
df1 = gcp2df("""{}""".format(query1), client)
df2 = gcp2df("""{}""".format(query2), client)
# dumb_dict = {
# "dumb":"dumb"
# }
# with open('dumb.json', "w") as outfile:
# json.dump(dumb_dict, outfile)
# os.environ["GOOGLE_APPLICATION_CREDENTIALS"]= 'dumb.json'
querycolumns = json.loads(querycolumns)
querycolumns = list(querycolumns.values())
features = pair(df1, df2, TT, querycolumns)
features['Similarity_score'] = features.sum(axis=1)
features = features[features['Similarity_score']>=SS].reset_index()
final = features[['level_0', 'level_1']]
final.rename(columns= {'level_0':'df1_index', 'level_1':'df2_index'}, inplace= True)
final['Unique_ID'] = [uuid.uuid4() for _ in range(len(final.index))]
final['Unique_ID'] = final['Unique_ID'].astype(str)
final['Similarity_Score'] = SS
final_duplicates = final['df1_index'].value_counts().max()
# insert(final,"test-ahmed-project.Record_Linkage.Matching_Indices")
message = "Mission accomplished!, your highest duplica is " + str(final_duplicates)
os.remove("service_account.json")
return {'message':message, 'final':json.loads(final.to_json()), 'df1':json.loads(df1.to_json()), 'df2':json.loads(df2.to_json())}
and this is the error:
Traceback (most recent call last):
File "C:\Users\HP\Desktop\Datalaksa\Tzu Ming\Flask exploring\Coud_Run_Example\env\lib\site-packages\flask\app.py", line 2548, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\HP\Desktop\Datalaksa\Tzu Ming\Flask exploring\Coud_Run_Example\env\lib\site-packages\flask\app.py", line 2528, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\HP\Desktop\Datalaksa\Tzu Ming\Flask exploring\Coud_Run_Example\env\lib\site-packages\flask\app.py", line 2525, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\HP\Desktop\Datalaksa\Tzu Ming\Flask exploring\Coud_Run_Example\env\lib\site-packages\flask\app.py", line 1822, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\HP\Desktop\Datalaksa\Tzu Ming\Flask exploring\Coud_Run_Example\env\lib\site-packages\flask\app.py", line 1820, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\HP\Desktop\Datalaksa\Tzu Ming\Flask exploring\Coud_Run_Example\env\lib\site-packages\flask\app.py", line 1796, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
File "C:\Users\HP\Desktop\Datalaksa\Tzu Ming\Flask exploring\Final_Coud_Run_Example\main.py", line 28, in query
result = Matching(params['query1'],params['query2'], params['SS'],params['TT'], params['service_account'], params['project_id'], params['querycolumns'])
File "C:\Users\HP\Desktop\Datalaksa\Tzu Ming\Flask exploring\Final_Coud_Run_Example\Record_Matching.py", line 75, in Matching
credentials = service_account.Credentials.from_service_account_info(service_account)
AttributeError: 'dict' object has no attribute 'Credentials'
127.0.0.1 - - [29/Nov/2022 18:50:01] "GET /query HTTP/1.1" 500 -
Traceback (most recent call last):
File "C:\Users\HP\Desktop\Datalaksa\Tzu Ming\Flask exploring\Coud_Run_Example\env\lib\site-packages\flask\app.py", line 2548, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\HP\Desktop\Datalaksa\Tzu Ming\Flask exploring\Coud_Run_Example\env\lib\site-packages\flask\app.py", line 2528, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\HP\Desktop\Datalaksa\Tzu Ming\Flask exploring\Coud_Run_Example\env\lib\site-packages\flask\app.py", line 2525, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\HP\Desktop\Datalaksa\Tzu Ming\Flask exploring\Coud_Run_Example\env\lib\site-packages\flask\app.py", line 1822, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\HP\Desktop\Datalaksa\Tzu Ming\Flask exploring\Coud_Run_Example\env\lib\site-packages\flask\app.py", line 1820, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\HP\Desktop\Datalaksa\Tzu Ming\Flask exploring\Coud_Run_Example\env\lib\site-packages\flask\app.py", line 1796, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
File "C:\Users\HP\Desktop\Datalaksa\Tzu Ming\Flask exploring\Final_Coud_Run_Example\main.py", line 28, in query
result = Matching(params['query1'],params['query2'], params['SS'],params['TT'], params['service_account'], params['project_id'], params['querycolumns'])
File "C:\Users\HP\Desktop\Datalaksa\Tzu Ming\Flask exploring\Final_Coud_Run_Example\Record_Matching.py", line 75, in Matching
credentials = service_account.Credentials.from_service_account_info(service_account)
AttributeError: 'dict' object has no attribute 'Credentials'
I tried using using a service account without a json file path, I'm expecting my code to accept the service account as a dictionary.

You get the error because you use the same variable name on your import and parameter name on Matching() function. Your import currently looks like this:
from google.oauth2 import service_account
Then on your function Matching(), you accept a parameter named service_account. Your code references the parameter and not the import. Your function currently looks like this:
def Matching(query1,query2, SS,TT, service_account, project_id, querycolumns):
...
...
credentials = service_account.Credentials.from_service_account_info(service_account)
To fix this, change the name of your parameter in Matching() so your code won't be confused which object to use. You can rewrite your function this way:
def Matching(query1,query2, SS,TT, sa, project_id, querycolumns):
...
...
credentials = service_account.Credentials.from_service_account_info(sa)

Related

Marshmallow for python giving ValueError: not enough values to unpack (expected 2, got 1)

I am using Marshmallow for serialization/deserialization purposes in the API I am building but I'm getting the above-stated error. Here are my Schema, Model, and Resource file for the same.
schemas/post.py
from marshmallow import Schema, fields, validate, post_dump
from schemas.user import UserSchema
class PostSchema(Schema):
class Meta:
ordered = True
id = fields.Int(dump_only=True)
body = fields.Str(required=True, validate=[validate.Length(max=500, min=1)])
created_at = fields.DateTime(dump_only=True)
updated_at = fields.DateTime(dump_only=True)
author = fields.Nested(UserSchema, attribute='user', dump_only=True, only=['id', 'username'])
#post_dump(pass_many=True)
def wrap_output_with_envelope(self, data, many, **kwargs):
if many:
return {'data': data}
return data
models/post.py
from database import db
class Post(db.Model):
__tablename__ = 'post'
id = db.Column(db.Integer, primary_key=True)
body = db.Column(db.String, nullable=False)
created_at = db.Column(db.DateTime(), nullable=False, server_default=db.func.now())
updated_at = db.Column(db.DateTime(), nullable=False, server_default=db.func.now(), onupdate=db.func.now())
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
#classmethod
def get_by_post_id(cls, id):
return cls.query.filter_by(id=id).first()
#classmethod
def get_all_posts(cls):
return cls.query.all()
def data(self):
return {'id': self.id, 'body': self.body, 'user_id': self.user_id}
def save(self):
db.session.add(self)
db.session.commit()
def delete(self):
db.session.delete(self)
db.session.commit()
and resources/post.py
from flask import request
from flask_restful import Resource
from http import HTTPStatus
from flask_jwt_extended import jwt_required, get_jwt_identity, jwt_optional
from models.post import Post
from schemas.post import PostSchema
post_schema = PostSchema()
post_list_schema = PostSchema(many=True)
class PostListResource(Resource):
def get(self):
posts = Post.get_all_posts()
return post_list_schema.dump(posts), HTTPStatus.OK
#jwt_required
def post(self):
json_data = request.get_json()
current_user = get_jwt_identity()
data, errors = post_schema.load(data=json_data)
if errors:
return {'message': "Validation errors", 'errors': errors}, HTTPStatus.BAD_REQUEST
post = Post(**data)
post.user_id = current_user
post.save()
return post_schema.dump(post), HTTPStatus.CREATED
I try sending the following JSON: {"body": "This is some text."} and the error I get is:
Traceback (most recent call last):
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask\app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask\app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask_restful\__init__.py", line 272, in error_router
return original_handler(e)
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask\app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask\_compat.py", line 38, in reraise
raise value.with_traceback(tb)
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask_restful\__init__.py", line 272, in error_router
return original_handler(e)
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask\app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask\_compat.py", line 38, in reraise
raise value.with_traceback(tb)
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask\app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask_restful\__init__.py", line 468, in wrapper
resp = resource(*args, **kwargs)
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask\views.py", line 89, in view
return self.dispatch_request(*args, **kwargs)
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask_restful\__init__.py", line 583, in dispatch_request
resp = meth(*args, **kwargs)
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask_jwt_extended\view_decorators.py", line 108, in wrapper
return fn(*args, **kwargs)
File "D:\blogposts\resources\post.py", line 23, in post
data, errors = post_schema.load(data=json_data)
ValueError: not enough values to unpack (expected 2, got 1)
Please help. Thanks!
You must have been following an outdated doc/tuto.
Since marshmallow 3, only data is returned. A ValidationError is raised in case of error.
Change
data, errors = post_schema.load(data=json_data)
if errors:
return {'message': "Validation errors", 'errors': errors}, HTTPStatus.BAD_REQUEST
into
try:
data = post_schema.load(data=json_data)
except ValidationError as exc:
return {'message': "Validation errors", 'errors': exc.messages}, HTTPStatus.BAD_REQUEST

ModuleNotFoundError: No module named 'MySQLdb' in Flask-sqlalchemy

I am just new in Flask, so I am trying to send data to the database using different tutorial source. I build simple blog type websites and my database server is http://localhost/phpmyadmin/. After I clicked on the submit button on contact.html. I got this error. So how can I fixed this error.
Traceback (most recent call last):
File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\sqlalchemy\util\_collections.py", line 1020, in __call__
return self.registry[key]
KeyError: 6528
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "F:\Flask\01\tut1.py", line 33, in contact
db.session.add(entry)
File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\sqlalchemy\orm\scoping.py", line 163, in do
return getattr(self.registry(), name)(*args, **kwargs)
File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\sqlalchemy\util\_collections.py", line 1022, in __call__
return self.registry.setdefault(key, self.createfunc())
File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\sqlalchemy\orm\session.py", line 3286, in __call__
return self.class_(**local_kw)
File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_sqlalchemy\__init__.py", line 138, in __init__
bind = options.pop('bind', None) or db.engine
File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_sqlalchemy\__init__.py", line 943, in engine
return self.get_engine()
File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_sqlalchemy\__init__.py", line 962, in get_engine
return connector.get_engine()
File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_sqlalchemy\__init__.py", line 556, in get_engine
self._engine = rv = self._sa.create_engine(sa_url, options)
File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_sqlalchemy\__init__.py", line 972, in create_engine
return sqlalchemy.create_engine(sa_url, **engine_opts)
File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\sqlalchemy\engine\__init__.py", line 500, in create_engine
return strategy.create(*args, **kwargs)
File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\sqlalchemy\engine\strategies.py", line 87, in create
dbapi = dialect_cls.dbapi(**dbapi_args)
File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\sqlalchemy\dialects\mysql\mysqldb.py", line 118, in dbapi
return __import__("MySQLdb")
ModuleNotFoundError: No module named 'MySQLdb'
My code is here
from flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:#localhost/blog'
db = SQLAlchemy(app)
class Contacts(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), nullable=False)
email = db.Column(db.String(255), nullable=False)
phone_number = db.Column(db.String(50), nullable=False)
message = db.Column(db.String(120), nullable=False)
date_created = db.Column(db.String(50), nullable=True )
#app.route('/contact/', methods=['GET','POST'])
def contact():
if request.method == 'POST':
name = request.form.get('name')
email = request.form.get('email')
phone_number = request.form.get('phone_number')
message = request.form.get('message')
entry = Contacts(name=name, email=email, phone_number=phone_number, message=message, date_created=datetime.now())
db.session.add(entry)
db.session.commit()
return render_template('contact.html')
app.run(debug=True)
Does anyone knows, how I get this error ?
Running command pip install pymysql and pip install mysqldbmodel help me to kicked this freaking(**) error.
Edit:
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:#localhost/blog'
I find this solution at ImportError: No module named MySQLdb
datetime.now: Does not return a String you need to convert it to String or change the type in the database to date like this
date_created = db.Column(db.DateTime, nullable=True )
I have used this and it worked very will with me
from flask import Flask, render_template, request,redirect
from flask_sqlalchemy import SQLAlchemy
import sqlite3
from datetime import *
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database1.db'
db = SQLAlchemy(app)
class Contacts(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), nullable=False)
email = db.Column(db.String(255), nullable=False)
phone_number = db.Column(db.String(50), nullable=False)
message = db.Column(db.String(120), nullable=False)
date_created = db.Column(db.DateTime, nullable=True )
db.create_all()
#app.route('/contact', methods=['GET','POST'])
def contact():
if request.method == 'POST':
name = request.form.get('name')
email = request.form.get('email')
phone_number = request.form.get('phone_number')
message = request.form.get('message')
entry = Contacts(name="name", email="email", phone_number="phone_number", message="message", date_created=datetime.now())
try:
db.session.add(entry)
db.session.commit()
db.session.close()
return render_template('h.html')
except:
return "Error"
app.run(debug=True)
You need to change the things i have changed like the render_template
if it did not work please provide you github

app engine standard environment call bigquery python

I am trying to deploy a simple standard app engine in python and from there to make bigquery queries through python bigquery client.
The code is as simple as these:
from __future__ import absolute_import
import webapp2
import os
from google.cloud import bigquery
class MainPage(webapp2.RequestHandler):
def get(self):
client = bigquery.Client(project = "ancient-ceiling-125223")
project_name = str(client.project)
query_job = client.query("select 1")
assert query_job.state == 'RUNNING'
iterator = query_job.result(timeout= 30)
rows = list(iterator)
self.response.write('nothing to see %s' % (project_name))
app = webapp2.WSGIApplication(
[('/', MainPage)], debug=True)
The error log: The error appears in the dummy query request
*('Connection broken: IncompleteRead(209 bytes read)', IncompleteRead(209 bytes read)) (/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.3/webapp2.py:1528)
Traceback (most recent call last):
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1511, in __call__
rv = self.handle_exception(request, response, e)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1505, in __call__
rv = self.router.dispatch(request, response)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1253, in default_dispatcher
return route.handler_adapter(request, response)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1077, in __call__
return handler.dispatch()
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 547, in dispatch
return self.handle_exception(e, self.app.debug)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 545, in dispatch
return method(*args, **kwargs)
File "/base/data/home/apps/s~ancient-ceiling-125223/20171115t104156.405543624689752939/main.py", line 35, in get
query_job = client.query("select 1")
File "/base/data/home/apps/s~ancient-ceiling-125223/20171115t104156.405543624689752939/lib/google/cloud/bigquery/client.py", line 986, in query
job._begin(retry=retry)
File "/base/data/home/apps/s~ancient-ceiling-125223/20171115t104156.405543624689752939/lib/google/cloud/bigquery/job.py", line 397, in _begin
method='POST', path=path, data=self._build_resource())
File "/base/data/home/apps/s~ancient-ceiling-125223/20171115t104156.405543624689752939/lib/google/cloud/bigquery/client.py", line 271, in _call_api
return call()
File "/base/data/home/apps/s~ancient-ceiling-125223/20171115t104156.405543624689752939/lib/google/api_core/retry.py", line 260, in retry_wrapped_func
on_error=on_error,
File "/base/data/home/apps/s~ancient-ceiling-125223/20171115t104156.405543624689752939/lib/google/api_core/retry.py", line 177, in retry_target
return target()
File "/base/data/home/apps/s~ancient-ceiling-125223/20171115t104156.405543624689752939/lib/google/cloud/_http.py", line 290, in api_request
headers=headers, target_object=_target_object)
File "/base/data/home/apps/s~ancient-ceiling-125223/20171115t104156.405543624689752939/lib/google/cloud/_http.py", line 183, in _make_request
return self._do_request(method, url, headers, data, target_object)
File "/base/data/home/apps/s~ancient-ceiling-125223/20171115t104156.405543624689752939/lib/google/cloud/_http.py", line 212, in _do_request
url=url, method=method, headers=headers, data=data)
File "/base/data/home/apps/s~ancient-ceiling-125223/20171115t104156.405543624689752939/lib/google/auth/transport/requests.py", line 186, in request
method, url, data=data, headers=request_headers, **kwargs)
File "/base/data/home/apps/s~ancient-ceiling-125223/20171115t104156.405543624689752939/lib/requests/sessions.py", line 502, in request
resp = self.send(prep, **send_kwargs)
File "/base/data/home/apps/s~ancient-ceiling-125223/20171115t104156.405543624689752939/lib/requests/sessions.py", line 652, in send
r.content
File "/base/data/home/apps/s~ancient-ceiling-125223/20171115t104156.405543624689752939/lib/requests/models.py", line 825, in content
self._content = bytes().join(self.iter_content(CONTENT_CHUNK_SIZE)) or bytes()
File "/base/data/home/apps/s~ancient-ceiling-125223/20171115t104156.405543624689752939/lib/requests/models.py", line 750, in generate
raise ChunkedEncodingError(e)
ChunkedEncodingError: ('Connection broken: IncompleteRead(209 bytes read)', IncompleteRead(209 bytes read))*
I could not make it work using python bigquery client library, Here is what I found working in standard app engine environment,
from __future__ import absolute_import
import webapp2
from googleapiclient.discovery import build
from oauth2client.client import GoogleCredentials
class MainPage(webapp2.RequestHandler):
def get(self):
credentials = GoogleCredentials.get_application_default()
service = build('bigquery', 'v2', credentials=credentials)
datasets = service.datasets().list(projectId="ancient-ceiling-125223").execute()
self.response.write('datasets: %s' % datasets)
app = webapp2.WSGIApplication(
[('/', MainPage)], debug=True)

SOAP/SSL/Python: do_open raise urllib2.URLError SSL_CTX_use_PrivateKey_file:system error

I am trying to use SOAP and a WSDL file to create a secure SSL HTTP network connection and call a login request. I am receiving a do_open error from urllib2 and I am unsure why. Please help!
Error as follows (from running SOAPconnect.py file below):
Traceback (most recent call last):
File "C:\Python27\connectSOAP.py", line 28, in <module>
response = client.service.login(loginInputParms)
File "C:\Python27\lib\site-packages\suds\client.py", line 542, in __call__
return client.invoke(args, kwargs)
File "C:\Python27\lib\site-packages\suds\client.py", line 602, in invoke
result = self.send(soapenv)
File "C:\Python27\lib\site-packages\suds\client.py", line 637, in send
reply = transport.send(request)
File "C:\Python27\lib\site-packages\suds\transport\http.py", line 77, in send
fp = self.u2open(u2request)
File "C:\Python27\transport.py", line 42, in u2open
return url.open(u2request, timeout=tm)
File "C:\Python27\lib\urllib2.py", line 391, in open
response = self._open(req, data)
File "C:\Python27\lib\urllib2.py", line 409, in _open
'_open', req)
File "C:\Python27\lib\urllib2.py", line 369, in _call_chain
result = func(*args)
File "C:\Python27\transport.py", line 15, in https_open
return self.do_open(self.getConnection, req)
File "C:\Python27\lib\urllib2.py", line 1148, in do_open
raise URLError(err)
urllib2.URLError: <urlopen error [Errno 336265218] _ssl.c:347: error:140B0002:SSL routines:SSL_CTX_use_PrivateKey_file:system lib>
Code as follows...
self.key = key
self.cert = cert
def https_open(self, req):
#Rather than pass in a reference to a connection class, we pass in
# a reference to a function which, for all intents and purposes,
# will behave as a constructor
return self.do_open(self.getConnection, req)
def getConnection(self, host, timeout=300):
return httplib.HTTPSConnection(host,
key_file=self.key,
cert_file=self.cert)
class HTTPSClientCertTransport(HttpTransport):
def __init__(self, key, cert, *args, **kwargs):
HttpTransport.__init__(self, *args, **kwargs)
self.key = key
self.cert = cert
def u2open(self, u2request):
"""
Open a connection.
#param u2request: A urllib2 request.
#type u2request: urllib2.Requet.
#return: The opened file-like urllib2 object.
#rtype: fp
"""
tm = self.options.timeout
url = urllib2.build_opener(HTTPSClientAuthHandler(self.key, self.cert))
if self.u2ver() < 2.6:
socket.setdefaulttimeout(tm)
return url.open(u2request)
else:
return url.open(u2request, timeout=tm)
Code to call request:
import transport
import cookielib
import urllib
import urllib2
from suds.client import Client
url = 'file:///C:/Python27/HPNA/api.wsdl.axis2'
pem = 'file:///C:/Python27/myappnopass.pem'
cert = 'file:///C:/Python27/myapp.crt'
client = Client(url, transport=transport.HTTPSClientCertTransport(pem, cert))
print client
loginInputParms = {
"username": "usrnamehere",
"password": "pwdhere"
}
response = client.service.login(loginInputParms)

Flask Security, Flask Mail AttributeError: 'NoneType' object has no attribute 'send'

I'm trying to implement the email function inside my Flask admin panel.
I've successfully integrated it within my admin panel but the problem is when I try to send any mail, it gives me below error with traceback.
builtins.AttributeError
AttributeError: 'NoneType' object has no attribute 'send'
File
"/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/flask/app.py", line 2000, in __call__
return self.wsgi_app(environ, start_response)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/flask/app.py", line 1991, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/flask/app.py", line 1567, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/flask/app.py", line 1988, in wsgi_app
response = self.full_dispatch_request()
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/flask/app.py", line 1641, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/flask/app.py", line 1544, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/flask/app.py", line 1639, in full_dispatch_request
rv = self.dispatch_request()
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/flask/app.py", line 1625, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/flask_admin/base.py", line 69, in inner
return self._run_view(f, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/flask_admin/base.py", line 368, in _run_view
return fn(self, *args, **kwargs)
File "/Users/genomics/PycharmProjects/side_project_one/app/security_layer.py", line 44, in index
send_email(admin_form.subject.data, admin_form.sender.data, [i], admin_form.content.data, None)
File "/Users/genomics/PycharmProjects/side_project_one/app/views/send_email.py", line 41, in send_email
mail.send(msg)
AttributeError: 'NoneType' object has no attribute 'send'
send_email.py
mail = None
def configure_mail(app):
# EMAIL SETTINGS
global mail
app.config.update(
MAIL_SERVER='smtp.gmail.com',
MAIL_PORT=587,
MAIL_USE_SSL=False,
MAIL_USERNAME='xxxx',
MAIL_PASSWORD='xxxx',
MAIL_USE_TLS=True,
DEFAULT_MAIL_SENDER='Danny from DPC'
#SECRET_KEY='abcdefd_thats_a_charming_secret_key',
)
mail = Mail(app)
def send_email(subject, sender, recipients, text_body, html_body):
msg = Message(subject, sender=sender, recipients=recipients)
msg.body = text_body
msg.html = html_body
mail.send(msg)
flask_security.py
from app.views.login_forms import AdminForm
from app.views.send_email import send_email
class EmailRegisterView(BaseView):
def is_accessible(self):
if not current_user.is_active or not current_user.is_authenticated:
return False
if current_user.has_role('admin_danny'):
return True
return False
#expose('/', methods=['GET', 'POST'])
def index(self):
admin_form = AdminForm()
if request.method == 'POST':
if admin_form.validate_on_submit():
recipients = [admin_form.recipient.data]
divided_recipients = recipients[0].split(',')
for i in divided_recipients:
send_email(admin_form.subject.data, admin_form.sender.data, [i], admin_form.content.data, None)
return self.render('admin.html', form=admin_form)
Ok, I found a solution.
So my importing structure was wrong
Inside def configure_mail, I have mail = Mail(app) set as global variable.
And that mail variable was not doing anything.
So what I did is, inside my app.init
app.config.update(
MAIL_SERVER='smtp.gmail.com',
MAIL_PORT=587,
MAIL_USE_SSL=False,
MAIL_USERNAME='something',
MAIL_PASSWORD='xxxxxx',
MAIL_USE_TLS=True,
DEFAULT_MAIL_SENDER='Danny from DPC'
# SECRET_KEY='abcdefd_thats_a_charming_secret_key',
)
mail = Mail(app)
and I called this above mail into send_email.py and everything is working fine. I still can't figure out what the exact error was but this did the trick.