FastAPI - render template in index.html - not working - sqlalchemy

Good day I am using FastAPI and I want to render the database contents on index.html - however I get the following error:
INFO: 127.0.0.1:55139 - "GET /?skip=0&limit=100 HTTP/1.1" 500 Internal Server Error
ERROR: Exception in ASGI application
Traceback (most recent call last):
File "/Users/barnaby/.local/share/virtualenvs/fastapi-example-6xjq_vv2/lib/python3.9/site-packages/uvicorn/protocols/http/h11_impl.py", line 394, in run_asgi
result = await app(self.scope, self.receive, self.send)
File "/Users/barnaby/.local/share/virtualenvs/fastapi-example-6xjq_vv2/lib/python3.9/site-packages/uvicorn/middleware/proxy_headers.py", line 45, in __call__
return await self.app(scope, receive, send)
File "/Users/barnaby/.local/share/virtualenvs/fastapi-example-6xjq_vv2/lib/python3.9/site-packages/fastapi/applications.py", line 190, in __call__
await super().__call__(scope, receive, send)
File "/Users/barnaby/.local/share/virtualenvs/fastapi-example-6xjq_vv2/lib/python3.9/site-packages/starlette/applications.py", line 111, in __call__
await self.middleware_stack(scope, receive, send)
File "/Users/barnaby/.local/share/virtualenvs/fastapi-example-6xjq_vv2/lib/python3.9/site-packages/starlette/middleware/errors.py", line 181, in __call__
raise exc from None
File "/Users/barnaby/.local/share/virtualenvs/fastapi-example-6xjq_vv2/lib/python3.9/site-packages/starlette/middleware/errors.py", line 159, in __call__
await self.app(scope, receive, _send)
File "/Users/barnaby/.local/share/virtualenvs/fastapi-example-6xjq_vv2/lib/python3.9/site-packages/starlette/middleware/cors.py", line 78, in __call__
await self.app(scope, receive, send)
File "/Users/barnaby/.local/share/virtualenvs/fastapi-example-6xjq_vv2/lib/python3.9/site-packages/starlette/exceptions.py", line 82, in __call__
raise exc from None
File "/Users/barnaby/.local/share/virtualenvs/fastapi-example-6xjq_vv2/lib/python3.9/site-packages/starlette/exceptions.py", line 71, in __call__
await self.app(scope, receive, sender)
File "/Users/barnaby/.local/share/virtualenvs/fastapi-example-6xjq_vv2/lib/python3.9/site-packages/starlette/routing.py", line 566, in __call__
await route.handle(scope, receive, send)
File "/Users/barnaby/.local/share/virtualenvs/fastapi-example-6xjq_vv2/lib/python3.9/site-packages/starlette/routing.py", line 227, in handle
await self.app(scope, receive, send)
File "/Users/barnaby/.local/share/virtualenvs/fastapi-example-6xjq_vv2/lib/python3.9/site-packages/starlette/routing.py", line 41, in app
response = await func(request)
File "/Users/barnaby/.local/share/virtualenvs/fastapi-example-6xjq_vv2/lib/python3.9/site-packages/fastapi/routing.py", line 188, in app
raw_response = await run_endpoint_function(
File "/Users/barnaby/.local/share/virtualenvs/fastapi-example-6xjq_vv2/lib/python3.9/site-packages/fastapi/routing.py", line 137, in run_endpoint_function
return await run_in_threadpool(dependant.call, **values)
File "/Users/barnaby/.local/share/virtualenvs/fastapi-example-6xjq_vv2/lib/python3.9/site-packages/starlette/concurrency.py", line 34, in run_in_threadpool
return await loop.run_in_executor(None, func, *args)
File "/usr/local/Cellar/python#3.9/3.9.0_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/concurrent/futures/thread.py", line 52, in run
result = self.fn(*self.args, **self.kwargs)
File "./sql_app/main.py", line 51, in read_notes
"title": title,
NameError: name 'title' is not defined
Main.py
from fastapi import FastAPI
from typing import List, Dict
from fastapi import Depends, FastAPI, HTTPException, Request, Response
from fastapi.responses import HTMLResponse
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy.orm import Session
from fastapi.templating import Jinja2Templates
from . import crud, models, schemas
from .database import SessionLocal, engine
models.Base.metadata.create_all(bind=engine)
templates = Jinja2Templates(directory="templates")
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
# Dependency
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
# #original function
# #app.get("/notes", response_model=List[schemas.Note])
# def read_notes(request: Request, skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
# notes = crud.get_notes(db=db, skip=skip, limit=limit)
# print(notes)
# return notes
#app.get("/", response_class=HTMLResponse)
def read_notes(request: Request, skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
notes = crud.get_notes(db=db, skip=skip, limit=limit)
print(notes)
return templates.TemplateResponse("index.html",{
"request": request,
"id": id,
"title": title,
"description": description
})
#app.post("/notes", response_model=schemas.Note, status_code=201)
def create_note(note: schemas.NoteCreate, db: Session = Depends(get_db)):
return crud.create_note(db=db, note=note)
#app.get("/notes/{note_id}", response_model=schemas.Note)
def read_user(note_id: int, db: Session = Depends(get_db)):
db_note = crud.get_note(db=db, note_id=note_id)
if db_note is None:
raise HTTPException(status_code=404, detail="Note not found")
return db_note
#app.delete("/notes/{note_id}", status_code=204)
async def delete_note(note_id: int, db: Session = Depends(get_db)):
return crud.delete_note(db=db, note_id=note_id)
#app.put("/notes/{note_id}", status_code=200)
async def put_note(note_id: int, note: schemas.NoteCreate, db: Session = Depends(get_db)):
db_note = schemas.Note(id = note_id, title= note.title, description=note.description)
crud.update_note(db=db, note=db_note)
#app.patch("/notes/{note_id}", status_code=200)
async def patch_note(note_id: int, note: schemas.NoteCreate, db: Session = Depends(get_db)):
print(note_id)
print(note.title)
print(note.description)
db_note = schemas.Note(id = note_id, title= note.title, description=note.description)
crud.update_note(db=db, note=db_note)
if __name__ == '__main__':
uvicorn.run("main:app", host="127.0.0.1", port=8000)
crud.py
from sqlalchemy.orm import Session
from . import models, schemas
def get_note(db: Session, note_id: int):
return db.query(models.Note).filter(models.Note.id == note_id).first()
def delete_note(db: Session, note_id: int):
db_note = db.query(models.Note).filter(models.Note.id == note_id).first()
db.delete(db_note)
db.commit()
return {}
def get_notes(db: Session, skip: int = 0, limit: int = 100):
return db.query(models.Note).offset(skip).limit(limit).all()
def create_note(db: Session, note: schemas.NoteCreate):
db_note = models.Note(title=note.title, description=note.description)
db.add(db_note)
db.commit()
db.refresh(db_note)
return db_note
def update_note(db: Session, note: schemas.Note):
db_note = db.query(models.Note).filter(models.Note.id == note.id).first()
db_note.title = note.title
db_note.description = note.description
db.commit()
db.refresh(db_note)
return db_note
schemas.py
class NoteBase(BaseModel):
title: str
description: str
class NoteCreate(NoteBase):
pass
class Note(NoteBase):
id: int
class Config:
orm_mode = True
models.py
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import relationship
from .database import Base
class Note(Base):
__tablename__ = "notes"
id = Column(Integer, primary_key=True, index=True)
title = Column(String, nullable=True, default="new")
description = Column(String, nullable=True, default="new")
index.html
{% extends 'layout.html' %} {% include 'header.html' %} {% block title %} Home {% endblock %} {% block body %}
<div class="container">
<div class="row">
<div class="col md-12">
<div class="jumbotron">
<table class="table">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">Title</th>
<th scope="col">Description</th>
</tr>
</thead>
<tbody>
<tr>
{% for note in notes%}
<td>{{notes.id}}</td>
<td>{{notes.title}}</td>
<td>{{notes.description}}</td>
</tr>
{% endfor %}
<tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
{% endblock %}
Is my schema/models set up incorrectly?
looking at this end point-- http://127.0.0.1:8000/notes i get the following displayed in index.html. However this is in list format.But somehow I am unable to render it via the HTML template.
[ { "title": "title 3", "description": "title 3 description", "id": 3 }, { "title": "title 1 updated", "description": "string", "id": 1 }, { "title": "Title updated 2", "description": "description updated2", "id": 2 }, { "title": "Note 4", "description": "Note 4 description", "id": 4 } ]
database.py
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
SQLALCHEMY_DATABASE_URL = "postgresql://postgres:123456789#localhost/notes"
engine = create_engine (SQLALCHEMY_DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

Your error is a result of an undefined variable title on line 51 of main.py in the read_notes function exactly as your stack trace indicates.
Rewrite your endpoint to do something like the following
#app.get("/", response_class=HTMLResponse)
def read_notes(request: Request, skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
notes = crud.get_notes(db=db, skip=skip, limit=limit)
return templates.TemplateResponse("index.html", {
"notes": notes,
})

I have changed the code accordingly.
#app.get("/", response_class=HTMLResponse)
def read_notes(request: Request, skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
notes = crud.get_notes(db=db, skip=skip, limit=limit)
return templates.TemplateResponse("index.html", {
"request": request,
"notes": notes,
})
Also had to change the for loop in index.html which made the table go bonkers..
{% extends 'layout.html' %} {% include 'header.html' %} {% block title %} Home {% endblock %} {% block body %}
<div class="container">
<div class="row">
<div class="col md-12">
<div class="jumbotron">
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Description</th>
</tr>
</thead>
<tbody>
{%for note in notes%}
<tr>
<td>{{note.id}}</td>
<td>{{note.title}}</td>
<td>{{note.description}}</td>
</tr>
{%endfor%}
</tbody>
</table>
</div>
</div>
</div>
</div>
{% endblock %}
Thank you for assisting. I really appreciate it...

Related

Unable to use method of a class in different class-missing 2 required positional arguments

I have two python classes:- One class(CloudLink) is responsible for sending JSON events to the app and another(ReadData) is responsible for building the JSON data.
The ReadData class will be using the CloudLink methods to send the JSON data to the App. But I'm getting error _buildJSONdata() missing 1 required positional argument: 'Data'.
ReadData class
from pyspark.sql import SparkSession
import functools
from pyspark.sql import DataFrame
from pyspark.sql.functions import explode
from cosmosconnect import azurecosmos
class ReadData:
#exception(logger)
def __init__(self):
self.spark_session = (
SparkSession.builder
.appName("readData")
.getOrCreate()
)
mssparkutils.fs.unmount('/mnt/test')
logger.info("Drive unmounted")
mssparkutils.fs.mount(
'abfss://abc#transl.dfs.core.windows.net/',
'/mnt/test',
{'linkedService': "linkCosmos"}
)
logger.info("Mounted Successfully")
self.input_directory = (f"synfs:/{mssparkutils.env.getJobId()}/mnt/test/input_path"
)
self.output_directory = (f"synfs:/{mssparkutils.env.getJobId()}/mnt/test/output_path"
)
'''
Reading the schema from csv file
'''
#exception(logger)
def readConfig(self):
try:
logger.info(f"Reading the Config present in {self.input_directory} ")
dfConfig = self.spark_session.read.option("multiline","true") \
.json(self.input_directory)
#for f in dfConfig.select("Entity","Query","Business_Rule").collect():
dfConfig=dfConfig.select(explode('Input').alias('Input_Data'))\
.select('Input_Data.Validation_Type','Input_Data.Entity','Input_Data.Query','Input_Data.Business_Rule')
for f in dfConfig.rdd.toLocalIterator():
#for index, f in dfConfig.toPandas().iterrows():
self.Validation_Type=f[0]
self.container=f[1]
self.query=f[2]
self.rule=f[3]
self.readCosmos(self)
except:
raise ValueError("")
#exception(logger)
def readCosmos(self,*params):
#from cosmosconnect import azurecosmos
#a=[]
linkedService='fg'
df=azurecosmos.cosmosConnect(linkedService,self.query,self.container)
df.cache()
if len(df.head(1)) >0:
outputpath=self.output_directory+'/'+self.container
df.coalesce(1).write.mode('overwrite').parquet(outputpath)
Status="Validation Failure"
Data= {"Validation_Type":[],"Status":[],"Container":[],"Business_Rule":[]}
Data["Validation_Type"].append(self.Validation_Type)
Data["Status"].append(Status)
Data["Container"].append(self.container)
Data["Business_Rule"].append(self.rule)
CloudLink._buildJSONdata(Data)
if __name__ == "__main__":
p = ReadData()
p.readConfig()
CloudLink class
import json
import datetime
import hashlib
import json
import sys
import traceback
import adal
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
import logging
from functools import wraps
import sys
def create_logger():
#create a logger object
#logger = logging.getLogger()
logger = logging.getLogger()
logger.setLevel(logging.INFO)
logfile = logging.FileHandler('exc_logger.log')
#logfile = logging.StreamHandler(sys.stdout)
fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
formatter = logging.Formatter(fmt)
logfile.setFormatter(formatter)
logger.addHandler(logfile)
return logger
logger = create_logger()
def exception(logger):
def decorator(func):
#wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except:
issue = "exception in "+func.__name__+"\n"
issue = issue+"-------------------------\
------------------------------------------------\n"
logger.exception(issue)
raise
return wrapper
return decorator
class CloudLink(object):
_token = None
_instance = None
http = None
cloudclient = TokenLibrary.getSecret("xxxx", "rtrt")
clientid = TokenLibrary.getSecret("xxxx", "tyty")
clientcredentials = TokenLibrary.getSecret("xxxx", "abcabc")
authority_url = TokenLibrary.getSecret("xxxx", "abab")
cloudtest = TokenLibrary.getSecret("xxxx", "yyyy")
#staticmethod
def getInstance():
if not CloudLink._instance:
CloudLink._instance = CloudLink()
return CloudLink._instance
def __init__(self):
retry_strategy = Retry(
total=3,
backoff_factor=0,
status_forcelist=[429, 500, 502, 503, 504],
allowed_methods=["HEAD", "GET", "OPTIONS"],
)
adapter = HTTPAdapter(max_retries=retry_strategy)
self.http = requests.Session()
self.http.mount("https://", adapter)
self.http.mount("http://", adapter)
print("Inside init")
def parseJSON(self, t):
try:
eventData = json.loads(t)
logger.info(f"Sending {eventData} to cloud")
self.sendToCloud(eventData)
except ValueError as e:
print("Error: %s Please validate JSON in https://www.jsonschemavalidator.net/"% e)
return None # or: raise
def sendToCloud(self, eventData):
cloudData = {"eventData": eventData, "metadata": self._buildMetadata()}
logger.info(f"Raising alert with data=({cloudData}")
response = self.http.post(
self.cloudtest, headers=self._buildHeaders(), json=cloudData
)
logger.info(f"cloud alert response={response}")
if response.status_code == 202 or response.status_code == 200:
logger.info("Mail sent to Cloud")
else:
raise Exception(f"Cloud reporting failed with Error {response}")
def _buildJSONdata(self,Data):
if len(Data) == 0:
raise Exception("JSON is empty")
else:
t = json.dumps(self.Data)
self.parseJSON(t)
def _buildMetadata(self):
return {
"messageType": "Send Email",
"messageVersion": "0.0.1",
"sender": "Send Email",
}
def _buildHeaders(self):
self._refreshADToken()
headers = {
"Authorization": "Bearer {}".format(self._token["accessToken"]),
"Content-type": "application/json",
"Accept": "text/plain",
}
return headers
def _refreshADToken(self):
def shouldRenew(token):
"""Returns True if the token should be renewed"""
expiresOn = datetime.datetime.strptime(
token["expiresOn"], "%Y-%m-%d %H:%M:%S.%f"
)
now = datetime.datetime.now()
return (expiresOn - now) < datetime.timedelta(minutes=5)
if not self._token or shouldRenew(self._token):
logger.info("Renewing credentials for Alerting")
result = None
try:
context = adal.AuthenticationContext(CloudLink.authority_url)
result = context.acquire_token_with_client_credentials(CloudLink.cloudclient, CloudLink.clientid,CloudLink.clientcredentials)
except Exception as e:
error = "Failed to renew client credentials."
logger.info(error)
raise
if result and "accessToken" in result:
self._token = result
else:
logger.error(
"Failed to acquire bearer token. accessToken not found in result object on renewing credentials."
)
raise Exception("Could not acquire a bearer token")

Flask Session does not save data across app.routes

I have been struggling with a problem in my code for a long time now and I cannot seem to figure out what I am doing/is going wrong.
So basically I am making a chat app with flask and socket.io. I wanted to use flask session to save data, but my data does not seem to save.
import os
from flask import Flask, render_template, request, session, redirect
from flask_socketio import SocketIO, emit
from flask_session import Session
app = Flask(__name__)
app.config["SECRET_KEY"] = os.getenv("SECRET_KEY")
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
socketio = SocketIO(app, manage_session=False)
Session(app)
users = []
chatrooms = []
#app.route("/", methods=["GET","POST"])
def index():
if request.method == "POST":
displayname = request.form.get("dname")
for user in users:
if displayname == user:
return render_template("index.html", error_message = "Displayname is already taken.")
session['displayname'] = displayname
session["logged_in"] = True
return render_template("main.html", displayname=displayname, chatrooms=chatrooms, users=users)
if request.method == "GET":
if 'displayname' in session:
displayname = session['displayname']
return redirect("/main")
return render_template("index.html")
#app.route("/main", methods=["GET", "POST"])
def main():
if request.method == "GET":
displayname = request.form.get("goback")
session['displayname'] = displayname
if displayname in users:
users.remove(displayname)
if 'chatroomname' in session:
chatroomname = session['chatroomname']
return redirect("/getchatroom")
return render_template("main.html", displayname=displayname, chatrooms=chatrooms, users=users)
if request.method == "POST":
displayname = request.form.get("makechatroom")
session['displayname'] = displayname
chatroomname = request.form.get("chatroomname")
for chatroom in chatrooms:
if chatroom == chatroomname:
error= "This chatroom already exists! Choose another name!"
return render_template("main.html", displayname=displayname, chatrooms=chatrooms, users=users, error=error)
chatrooms.append(chatroomname)
session['chatroomname'] = chatroomname
users.append(displayname)
return render_template("chatroom.html", displayname=displayname, chatroomname=chatroomname, users=users)
#app.route("/getchatroom", methods=["POST"])
def getchatroom():
if request.method == "POST":
chatroomname = request.form.get("openchatroom")
session['chatroomname'] = chatroomname
displayname = request.form.get("disname")
session['displayname'] = displayname
users.append(displayname)
return render_template("chatroom.html", displayname=displayname, chatroomname=chatroomname, users=users)
#app.route("/logout", methods=["GET"])
def logout():
displayname = request.form.get("logout")
if displayname in users:
users.remove(displayname)
session.pop('username', None)
session["logged_in"] = False
return redirect("/")
I don't really know if the HTML is relevant, as it doesn't seem to be an issue that has to do with the HTML.
This is my error message:
File "C:\Users\linda\OneDrive\Bureaublad\project2\venv\Lib\site-packages\flask\app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\linda\OneDrive\Bureaublad\project2\venv\Lib\site-packages\flask_socketio\__init__.py", line 45, in __call__
return super(_SocketIOMiddleware, self).__call__(environ,
File "C:\Users\linda\OneDrive\Bureaublad\project2\venv\Lib\site-packages\engineio\middleware.py", line 74, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\linda\OneDrive\Bureaublad\project2\venv\Lib\site-packages\flask\app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\linda\OneDrive\Bureaublad\project2\venv\Lib\site-packages\flask\app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\linda\OneDrive\Bureaublad\project2\venv\Lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Users\linda\OneDrive\Bureaublad\project2\venv\Lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\linda\OneDrive\Bureaublad\project2\venv\Lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\linda\OneDrive\Bureaublad\project2\venv\Lib\site-packages\flask\app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\linda\OneDrive\Bureaublad\project2\venv\Lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Users\linda\OneDrive\Bureaublad\project2\venv\Lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\linda\OneDrive\Bureaublad\project2\venv\Lib\site-packages\flask\app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\linda\OneDrive\Bureaublad\project2\application.py", line 47, in main
displayname = session['displayname']
File "C:\Users\linda\OneDrive\Bureaublad\project2\venv\Lib\site-packages\werkzeug\local.py", line 377, in <lambda>
__getitem__ = lambda x, i: x._get_current_object()[i]
KeyError: 'displayname'
Thanks in advance for everyone trying to help!
xx Linda
There is a nasty bug in cachelib of python 2.7 version.
Exception is suppressed in lib\site-packages\cachelib\file.py", line 158, in set
Someone tried to fix this problem https://github.com/fengsp/flask-session/issues/119, but "fix" broke the code even more (My interpreter raises 'ModuleException `os` has no attribute `replace`').
So, my solution is just replace broken functions like that (simply paste after your imports):
def _hotfix(old, new):
try:
os.rename(old, new)
except WindowsError as e:
if e.errno == 17:
os.remove(new)
os.rename(old, new)
else:
class UniverseDestructionException(Exception):
pass
raise UniverseDestructionException
os.replace = os.rename = _hotfix
another reminder that python2.7 is no longer supported

Odoo V11 restapi - TypeError(repr(o) + “ is not JSON serializable”)

Am using odoo v11 integrating with restapi though working fine in CRUD operations when getting report data with error
file.py
def generate_report(self, xml_id, ids):
self_reports = {}
self_reports = {'result': False, 'state': False, 'exception': None}
try:
result, format = request.env.ref(xml_id).sudo().render_qweb_pdf([ids])
if not result:
tb = sys.exc_info()
self_reports['exception'] = odoo.exceptions.DeferredException('RML is not available at specified location or not enough data to print!', tb)
self_reports['result'] = result
self_reports['format'] = format
self_reports['state'] = True
self_reports.update({'id': ids})
except Exception as exception:
_logger.exception('Exception: %s\n', exception)
if hasattr(exception, 'name') and hasattr(exception, 'value'):
self_reports['exception'] = odoo.exceptions.DeferredException(tools.ustr(exception.name), tools.ustr(exception.value))
else:
tb = sys.exc_info()
self_reports['exception'] = odoo.exceptions.DeferredException(tools.exception_to_unicode(exception), tb)
self_reports['state'] = True
exc = self_reports['exception']
if exc:
raise UserError('%s: %s' % (exc.message, exc.traceback))
if self_reports['state']:
if tools.config['reportgz']:
import zlib
res2 = zlib.compress(result)
else:
if isinstance(result, str):
res2 = result.encode('latin1', 'replace')
else:
res2 = result
if res2:
self_reports['result'] = base64.encodestring(res2)
return self_reports
def get_response(self, status_code, status, data=None):
"""Returns Response Object with given status code and status"""
response = Response()
response.status = status
if data:
response.data = isinstance(data, str) and data or json.dumps(data)
response.status_code = status_code
return response
this is data format
list: [{'exception': None, 'state': True, 'id': 3, 'format': 'pdf', 'result':
b'SlZCRVJpMHhMak1LTVNBd0lHOWlhZ284UEFvdlZIbHdaU0F2VUdGblpYTUtMME52ZFc1MElERUtM\nMHRwWkh
NZ1d5QXpJREFnVWlCZApDajQrQ21WdVpHOWlhZ295SURBZ2IySnFDanc4Q2k5UWNtOWtk\nV05sY2lBb1VIbFFSR
Vl5S1FvK1BncGxibVJ2WW1vS015QXdJRzlpCmFnbzhQQW92VW1WemIzVnlZ\nMlZ6SURVZ01DQlNDaTlCYm01dmR
ITWdNVGdnTUNCU0NpOVFZWEpsYm5RZ01TQXdJRklLTDFSNWNH\nVWcKTDFCaFoyVUtMMDFsWkdsaFFtOTRJR
nNnTUNBd0lEWXhNaUEzT1RJZ1hRb3ZRMjl1ZEdWdWRI\nTWdNVGtnTUNCU0NqNCtDbVZ1Wkc5aQphZ28wSUR
BZ2IySnFDanc4Q2k5VWVYQmxJQzlEWVhSaGJH\nOW5DaTlRWVdkbGN5QXhJREFnVWdvK1BncGxibVJ2WW1vS05T
QXdJRzlpCmFnbzhQQW92UTI5c2Iz\nSlRjR0ZqWlNBOFBBb3ZRMU53SUM5RVpYWnBZMlZTUjBJS0wwTlRjR2NnTD
BSbGRtbGpaVWR5WVhr\nS0wxQkQKVTNBZ05pQXdJRklLUGo0S0wwVjRkRWRUZEdGMFpTQThQQW92UjFOaElEY
2dNQ0JTQ2o0\nK0NpOUdiMjUwSUR3OENpOUdPQ0E0SURBZwpVZ292UmpjZ01UTWdNQ0JTQ2o0K0NpOVFZWFI ...
Error Traceback:
File "E:\Odoo\odoo11\addons\restapi\controllers\main.py", line 343, in call_report
return self.get_response(200, str(200), {'report': datas})
File "E:\Odoo\odoo11\addons\restapi\controllers\main.py", line 135, in get_response
response.data = isinstance(data, str) and data or json.dumps(data)
File "C:\Program Files\Python\Python35\lib\json\__init__.py", line 230, in dumps
return _default_encoder.encode(obj)
File "C:\Program Files\Python\Python35\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Program Files\Python\Python35\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "C:\Program Files\Python\Python35\lib\json\encoder.py", line 180, in default
raise TypeError(repr(o) + " is not JSON serializable")
I need the pdf report in binary data in api response , getting error in response data. Please anyone help me to resolve this
This is because you might you forget to import json lib. In your header declare like import json this might help you to solve your error.

Using Django Rest Framework with ForeignKey's

I am trying to use the django rest framework to create a Module model, but I can't get the JSON formatted correctly.
I create a lecture and a lab and then try to make a module with the lecture and lab. But I get an error (Cannot add "": instance is on database "default", value is on database "None")
Here is what I am trying for the JSON content.
{
"title": "First Module",
"labs": [
{
"title": "First Lab",
"duration": 10.0,
"description": "This is the first lab."
}
],
"lectures": [
{
"title": "First Lecture",
"duration": 0.0,
"description": "This is the first lecture."
}
]
}
class Lab(models.Model):
title = models.CharField(max_length=255)
duration = models.FloatField(help_text=_("Duration of Lab in Hours"), blank=True, null=True)
description = models.TextField(null=True, blank=True)
def __unicode__(self):
return self.title
class Lecture(models.Model):
title = models.CharField(max_length=255)
duration = models.FloatField(help_text=_("Duration of Lecture in Hours"), blank=True, null=True)
description = models.TextField(null=True, blank=True)
def __unicode__(self):
return self.title
class Module(models.Model):
title = models.CharField(max_length=255)
labs = models.ManyToManyField(Lab, related_name='modules', blank=True, null=True)
lectures = models.ManyToManyField(Lecture, related_name='modules', blank=True, null=True)
def __unicode__(self):
return self.title
class LabSerializer(serializers.ModelSerializer):
class Meta:
model = Lab
fields = ('title', 'duration', 'description')
class LectureSerializer(serializers.ModelSerializer):
class Meta:
model = Lecture
fields = ('title', 'duration', 'description')
class ModuleSerializer(serializers.ModelSerializer):
labs = LabSerializer(many=True, required=False)
lectures = LectureSerializer(many=True, required=False)
class Meta:
model = Module
fields = ('title', 'labs', 'lectures')
Traceback:
File "/home/siecje/virtualenv/ccafe/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
114. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/siecje/virtualenv/ccafe/local/lib/python2.7/site-packages/django/views/generic/base.py" in view
69. return self.dispatch(request, *args, **kwargs)
File "/home/siecje/virtualenv/ccafe/local/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view
57. return view_func(*args, **kwargs)
File "/home/siecje/virtualenv/ccafe/local/lib/python2.7/site-packages/rest_framework/views.py" in dispatch
400. response = self.handle_exception(exc)
File "/home/siecje/virtualenv/ccafe/local/lib/python2.7/site-packages/rest_framework/views.py" in dispatch
397. response = handler(request, *args, **kwargs)
File "/home/siecje/virtualenv/ccafe/local/lib/python2.7/site-packages/rest_framework/generics.py" in post
468. return self.create(request, *args, **kwargs)
File "/home/siecje/virtualenv/ccafe/local/lib/python2.7/site-packages/rest_framework/mixins.py" in create
54. self.object = serializer.save(force_insert=True)
File "/home/siecje/virtualenv/ccafe/local/lib/python2.7/site-packages/rest_framework/serializers.py" in save
596. self.save_object(self.object, **kwargs)
File "/home/siecje/virtualenv/ccafe/local/lib/python2.7/site-packages/rest_framework/serializers.py" in save_object
995. setattr(obj, accessor_name, object_list)
File "/home/siecje/virtualenv/ccafe/local/lib/python2.7/site-packages/django/db/models/fields/related.py" in __set__
840. manager.add(*value)
File "/home/siecje/virtualenv/ccafe/local/lib/python2.7/site-packages/django/db/models/fields/related.py" in add
581. self._add_items(self.source_field_name, self.target_field_name, *objs)
File "/home/siecje/virtualenv/ccafe/local/lib/python2.7/site-packages/django/db/models/fields/related.py" in _add_items
640. (obj, self.instance._state.db, obj._state.db))
Exception Type: ValueError at /modules/
Exception Value: Cannot add "<Lab: First Lab>": instance is on database "default", value is on database "None"

Error in creator function when trying to adapt sqlalchemy's polymorphic association example

I am looking at http://www.sqlalchemy.org/trac/browser/examples/generic_associations/discriminator_on_association.py and trying to adapt the example to one that is generic and can be reused. So I attempted to abstract all the classes. However there seems to be an error in the new function of the creator object.
Can anyone please help me how to repair this? Otherwise, if I know what is wrong, I guess it will be a good candidate to include in the SQLalchemy recipes.
ERROR:
Traceback (most recent call last):
File "sqlalchemyex.py", line 136, in <module>
zip="95732")
File "<string>", line 4, in __init__
File "/home/ahmed/dev/pyrenv/lib/python2.6/site-packages/SQLAlchemy-0.6.6-py2.6.egg/sqlalchemy/orm/state.py", line 111, in initialize_instance
return manager.events.original_init(*mixed[1:], **kwargs)
File "/home/ahmed/dev/pyrenv/lib/python2.6/site-packages/SQLAlchemy-0.6.6-py2.6.egg/sqlalchemy/ext/declarative.py", line 1378, in _declarative_constructor
setattr(self, k, kwargs[k])
File "/home/ahmed/dev/pyrenv/lib/python2.6/site-packages/SQLAlchemy-0.6.6-py2.6.egg/sqlalchemy/ext/associationproxy.py", line 195, in __set__
setattr(obj, self.target_collection, creator(values))
File "sqlalchemyex.py", line 28, in <lambda>
discriminator=discriminator)
TypeError: object.__new__() takes no parameters
from sqlalchemy.schema import Column, ForeignKey
from sqlalchemy.types import String, Integer
from sqlalchemy.ext.declarative import declared_attr, declarative_base
from sqlalchemy.orm import relationship, backref
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.engine import create_engine
from sqlalchemy.orm.session import sessionmaker
import os
class AssociationBase(object):
discriminator = Column(String)
"""Refers to the type of parent."""
#classmethod
def creator(cls, discriminator):
"""Provide a 'creator' function to use with
the association proxy."""
return lambda associateds:AssociationBase(
associateds=associateds,
discriminator=discriminator)
#property
def parent(self):
"""Return the parent object."""
return getattr(self, "%s_parent" % self.discriminator)
'''
#property
def associateds(self):
return getattr(self, "backref_%s" % self.discriminator)
'''
class HasPolymorphicParents(object):
#declared_attr
def association_id(self):
cls = self
foreignkey_assoc_id = "{0}_association.id".format(cls.__name__)
return Column(Integer, ForeignKey(foreignkey_assoc_id))
#declared_attr
def association(self):
cls = self
association_class = "{0}Association".format(cls.__name__)
return relationship(association_class,
backref="associateds".format(cls.__name__))
parent = association_proxy("association", "parent")
class HasAssociatedsMixin(object):
#declared_attr
def association_id(self):
cls = self
associated_classname = cls.__associated__
foreignkey_assoc_id = "{0}_association.id".format(associated_classname)
return Column(Integer, ForeignKey(foreignkey_assoc_id))
#declared_attr
def association(self):
cls = self
discriminator = cls.__name__.lower()
associated_classname = cls.__associated__
##########
assoc_rel = 'associateds'
assoc_proxy = association_proxy('association', assoc_rel,
creator=self.__assoc_cls__.creator(discriminator)
)
setattr(cls, assoc_rel, assoc_proxy)
##########
association_classname = "{0}Association".format(associated_classname)
return relationship(association_classname,
backref=backref("%s_parent" % discriminator, uselist=False))
DecBase = declarative_base()
class AddressAssociation(DecBase, AssociationBase, ):
__tablename__ = "Address_association"
id = Column(Integer, primary_key=True)
class Address(HasPolymorphicParents, DecBase):
__tablename__ = 'Addresses'
id = Column(Integer, primary_key=True)
street = Column(String)
city = Column(String)
zip = Column(String)
class Customer(HasAssociatedsMixin, DecBase):
__tablename__ = 'Customers'
__associated__ = 'Address'
__assoc_rel__ = 'addresses'
__assoc_cls__ = AddressAssociation
id = Column(Integer, primary_key=True)
name = Column(String)
class Supplier(HasAssociatedsMixin, DecBase):
__tablename__ = 'Suppliers'
__associated__ = 'Address'
__assoc_rel__ = 'addresses'
__assoc_cls__ = AddressAssociation
id = Column(Integer, primary_key=True)
name = Column(String)
company_name = Column(String)
os.environ['PYTHONINSPECT'] = 'True'
eng = create_engine('sqlite://')
DecBase.metadata.create_all(eng)
session = sessionmaker(bind=eng)()
session.add_all([
Customer(
name='customer 1',
associateds=[
Address(
street='123 anywhere street',
city="New York",
zip="10110"),
Address(
street='40 main street',
city="San Francisco",
zip="95732")
]
),
Supplier(
company_name="Ace Hammers",
associateds=[
Address(
street='2569 west elm',
city="Detroit",
zip="56785")
]
),
])
session.commit()
for customer in session.query(Customer):
for address in customer.addresses:
print address
print address.parent
This is the error what you get?
Traceback (most recent call last):
File "/tmp/test4.py", line 134, in <module>
associateds=[
File "<string>", line 4, in __init__
File "/usr/lib/python2.7/site-packages/sqlalchemy/orm/state.py", line 98, in initialize_instance
return manager.original_init(*mixed[1:], **kwargs)
File "/usr/lib/python2.7/site-packages/sqlalchemy/ext/declarative.py", line 1388, in _declarative_constructor
setattr(self, k, kwargs[k])
File "/usr/lib/python2.7/site-packages/sqlalchemy/ext/associationproxy.py", line 201, in __set__
setattr(obj, self.target_collection, creator(values))
File "/tmp/test4.py", line 23, in <lambda>
discriminator=discriminator)
TypeError: object.__new__() takes no parameters