How to change the printed qweb filename - python

How to change the printed qweb filename depends on the source document field name?
Im in the model stock.picking
So when i click the print -> Delivery note, then the qweb will be printed, but te filename will be depends on the Source document field.
Here i present the picture that explain what i mean.
EXAMPLE

You can give dynamic report name using configuration, but it will apply when you print one report.
Below is the example to Print custom name in report.Create one field in ir.actions.report.xml, in which user can configure report name.
from openerp import models, fields
class IrActionsReportXml(models.Model):
_inherit = 'ir.actions.report.xml'
download_filename = fields.Char(
'Download filename')
Now you need to create two files.
Report Controller
from openerp import http
from openerp.addons.mail.models import mail_template
from openerp.addons.report.controllers.main import ReportController
from openerp.addons.web.controllers.main import content_disposition
class ReportController(ReportController):
#http.route([
'/report/<path:converter>/<reportname>',
'/report/<path:converter>/<reportname>/<docids>',
])
def report_routes(self, reportname, docids=None, converter=None, **data):
response = super(ReportController, self).report_routes(
reportname, docids=docids, converter=converter, **data)
if docids:
docids = [int(i) for i in docids.split(',')]
report_xml = http.request.session.model('ir.actions.report.xml')
report_ids = report_xml.search(
[('report_name', '=', reportname)])
for report in report_xml.browse(report_ids):
if not report.download_filename:
continue
objects = http.request.session.model(report.model)\
.browse(docids or [])
generated_filename = mail_template.mako_template_env\
.from_string(report.download_filename)\
.render({
'objects': objects,
'o': objects[:1],
'object': objects[:1],
'ext': report.report_type.replace('qweb-', ''),
})
response.headers['Content-Disposition'] = content_disposition(
generated_filename)
return response
#http.route(['/report/download'])
def report_download(self, data, token):
response = super(ReportController, self).report_download(data, token)
# if we got another content disposition before, ditch the one added
# by super()
last_index = None
for i in range(len(response.headers) - 1, -1, -1):
if response.headers[i][0] == 'Content-Disposition':
if last_index:
response.headers.pop(last_index)
last_index = i
return response
2.Report.py
import json
from openerp import http
from openerp.addons.web.controllers import main
from openerp.addons.mail.models import mail_template
class Reports(main.Reports):
#http.route('/web/report', type='http', auth="user")
#main.serialize_exception
def index(self, action, token):
result = super(Reports, self).index(action, token)
action = json.loads(action)
context = dict(http.request.context)
context.update(action["context"])
report_xml = http.request.env['ir.actions.report.xml']
reports = report_xml.search([
('report_name', '=', action['report_name']),
('download_filename', '!=', False)])
for report in reports:
objects = http.request.session.model(context['active_model'])\
.browse(context['active_ids'])
generated_filename = mail_template.mako_template_env\
.from_string(report.download_filename)\
.render({
'objects': objects,
'o': objects[0],
'object': objects[0],
})
result.headers['Content-Disposition'] = main.content_disposition(
generated_filename)
return result
Odoo community Providing us a default module for report custom name. you can directly install this module and set report name like : ${o.name}
Here o means your record.
Below is a link of odoo community module.
https://www.odoo.com/apps/modules/9.0/report_custom_filename/
This may help you.

try attachment in your reprot to change report file name as your desired name.
<report
string="Delivery Slip"
id="action_report_delivery"
model="stock.picking"
report_type="qweb-pdf"
name="stock.report_deliveryslip"
file="stock.report_deliveryslip"
attachment="'Custom Text...'+'.pdf')"
/>

Here is my code which works for different reportname in the same model. So the filename only changes for the certain filename.
>
from openerp.addons.web.http import Controller, route, request
from openerp.addons.web.controllers.main import _serialize_exception
from openerp.osv import osv
from openerp.addons.report.controllers.main import ReportController
from openerp import http
import simplejson
import logging
class SponsorReportController(ReportController):
#route(['/report/download'], type='http', auth="user")
def report_download(self, data, token):
requestcontent = simplejson.loads(data)
url, type = requestcontent[0], requestcontent[1]
logging.info(url)
logging.info(type)
response = ReportController().report_download(data, token)
if len(url.split('/report/pdf/')) > 1 and type == 'qweb-pdf':
reportname = url.split('/report/pdf/')[1].split('?')[0]
reportname, docids = reportname.split('/')
logging.info(reportname)
assert docids
logging.info(docids)
if reportname == 'pci_stock_picking_report.report_delivery_note':
partner_obj = http.request.env['stock.picking']
object = partner_obj.browse(int(docids))
filename = "No."+(object.origin)
response.headers.set('Content-Disposition', 'attachment; filename=%s.pdf;' % filename)
return response

Related

How can I solve the Not found problem when getting from pytest-django through pk?

I have a problem with django-pytest
I'm using, djnago-rest-framework
There is a problem testing the details. As shown in the code below, I entered the same details, detail1, detail2, and detail3 codes. However, only detail1 succeeds and detail2, detail3 indicates that '/api/v1/stats/1/' could not be found. It also occurs when implementing delete. I am curious about the cause and solution of this error.
enter image description here
// tests/test_apis.py
import json
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from stats.models import Stats
class StatsApiTests(APITestCase):
def setUp(self):
Stats.objects.get_or_create(blockshots=1, memo='test1')
Stats.objects.get_or_create(blockshots=2, memo='test2')
self.create_read_url = reverse('api:stats:stats-list')
self.read_update_delete_url = reverse('api:stats:stats-detail', kwargs={'pk': '1'})
def test_detail1(self):
response = self.client.get(self.read_update_delete_url)
data = json.loads(response.content)
content = {
'blockshots': 1,
'memo': 'test1',
}
self.assertEqual(data, content)
def test_detail2(self):
response = self.client.get(self.read_update_delete_url)
data = json.loads(response.content)
content = {
'blockshots': 1,
'memo': 'test1',
}
self.assertEqual(data, content)
def test_detail3(self):
response = self.client.get(self.read_update_delete_url)
data = json.loads(response.content)
content = {
'blockshots': 1,
'memo': 'test1',
}
self.assertEqual(data, content)
def test_list(self):
response = self.client.get(self.create_read_url)
self.assertContains(response, 'test1')
self.assertContains(response, 'test2')
Its hard to know what your actual implementation for read_update_delete_url, hence I assume it is looking up the resource by primary key. In that case, you can simply add the primary key in the url like this:
stat_one, _ = Stats.objects.get_or_create(blockshots=1, memo='test1')
stat_two, _ = Stats.objects.get_or_create(blockshots=2, memo='test2')
self.read_update_delete_url = reverse('api:stats:stats-detail', kwargs={'pk': stat_one.pk})
Basically, get_or_create returns the object and the state of the object (created or not). You can use the object's id as the parameter of reverse function.

Importing Json into Django Database from url only imports parts of the data and says the rest is up to date but it isn't

I wrote a script which will basically import data from a json file and store it in the database of my Django Application.
I'm simply pointing to a json file and i'm adding "facilities" if they don't exist or they get updated if the last modified date changes.
It worked perfectly fine until i couldn't import the json file locally anymore and made some smaller changes to use an external json file.
When i run the importer now it will only import the first two facilities and then tell me that all others are up to date even though they don't exist. I even modified and tested the json file manually to make sure it is not caused by a bug inside the json file.
I will add the old code plus the modified code below.
One of the main differences is that this part is now at the very bottom in the new version after the if statement:
for key, data_object in data.items():
And also that i'm using "import requests" in the new version with the following code at the bottom of the file. My feeling is that i made a mistake right there:
def handle(self, *args, **options):
"""
Call the function to import data from json url
"""
headers = {'Content-Type': 'application/json'}
response = requests.get(
url=IMPORT_URL,
headers=headers,
)
data = response.json()
for key, data_object in data.items():
self.import_facility_from_file(data_object)
New Version:
import requests
import json
from leads.models import Facility, FacilityAddress, FacilityInspectionInfo, FacilityComplaints
from django.core.management.base import BaseCommand
IMPORT_URL = 'https://importerdomain.test/test.json'
class Command(BaseCommand):
def import_facility_from_file(self, data):
UUID = data.get('UUID', None)
Name = data.get('Name', None)
IssuedNumber = data.get('IssuedNumber', None)
Capacity = data.get('Capacity', None)
Licensee = data.get('Licensee', None)
Email = data.get('Email', None)
AdministratorName = data.get('AdministratorName', None)
TelephoneNumber = data.get('TelephoneNumber', None)
ClosedTimestamp = data.get('ClosedTimestamp', None)
MostRecentLicenseTimestamp = data.get('MostRecentLicenseTimestamp', None)
ImporterLastModifiedTimestamp = data.get('ImporterLastModifiedTimestamp', None)
PrimaryAddress = data["AddressInfo"]["PrimaryAddress"]
SecondaryAddress = data["AddressInfo"]["SecondaryAddress"]
City = data["AddressInfo"]["City"]
RegionOrState = data["AddressInfo"]["RegionOrState"]
PostalCode = data["AddressInfo"]["PostalCode"]
Geolocation = data["AddressInfo"]["Geolocation"]
ComplaintRelatedVisits = data["InspectionInfo"]["ComplaintRelatedVisits"]
InspectionRelatedVisits = data["InspectionInfo"]["InspectionRelatedVisits"]
NumberOfVisits = data["InspectionInfo"]["NumberOfVisits"]
LastVisitTimestamp = data["InspectionInfo"]["LastVisitTimestamp"]
ComplaintsTypeA = data["Complaints"]["ComplaintsTypeA"]
ComplaintsTypeB = data["Complaints"]["ComplaintsTypeB"]
SubstantiatedAllegations = data["Complaints"]["SubstantiatedAllegations"]
TotalAllegations = data["Complaints"]["TotalAllegations"]
if Facility.objects.filter(ImporterLastModifiedTimestamp=ImporterLastModifiedTimestamp):
msg = "\n\nfacility exists and is up to date: {}\n{}".format(Name, str())
print(msg)
else:
print("UPDATE")
facility, facility_created = Facility.objects.update_or_create(UUID=UUID,
defaults={
'Name': Name,
'IssuedNumber': IssuedNumber,
'Capacity': Capacity,
'Licensee': Licensee,
'Email': Email,
'AdministratorName': AdministratorName,
'TelephoneNumber': TelephoneNumber,
'ClosedTimestamp': ClosedTimestamp,
'MostRecentLicenseTimestamp': MostRecentLicenseTimestamp,
'ImporterLastModifiedTimestamp': ImporterLastModifiedTimestamp
}
)
facility_address, address_created = FacilityAddress.objects.update_or_create(AddressInfo=facility,
defaults={
'PrimaryAddress': PrimaryAddress,
'SecondaryAddress': SecondaryAddress,
'City': City,
'RegionOrState': RegionOrState,
'PostalCode': PostalCode,
'Geolocation': Geolocation,
'AddressInfo': facility
}
)
facility_inspection, inspection_created = FacilityInspectionInfo.objects.update_or_create(InspectionInfo=facility,
defaults={
'ComplaintRelatedVisits': ComplaintRelatedVisits,
'InspectionRelatedVisits': InspectionRelatedVisits,
'NumberOfVisits': NumberOfVisits,
'LastVisitTimestamp': LastVisitTimestamp,
'InspectionInfo': facility
}
)
facility_complaints, complaints_created = FacilityComplaints.objects.update_or_create(Complaints=facility,
defaults={
'ComplaintsTypeA': ComplaintsTypeA,
'ComplaintsTypeB': ComplaintsTypeB,
'SubstantiatedAllegations': SubstantiatedAllegations,
'TotalAllegations': TotalAllegations,
'Complaints': facility
}
)
def handle(self, *args, **options):
"""
Call the function to import data from json url
"""
headers = {'Content-Type': 'application/json'}
response = requests.get(
url=IMPORT_URL,
headers=headers,
)
data = response.json()
for key, data_object in data.items():
self.import_facility_from_file(data_object)
Old Version
import os
import json
import traceback
from data_import.models import Facility, FacilityAddress, FacilityInspectionInfo, FacilityComplaints
from django.core.management.base import BaseCommand
from datetime import datetime
from jsontest.settings import BASE_DIR, STATIC_URL
class Command(BaseCommand):
def import_facility_from_file(self):
print("BASE", BASE_DIR)
data_folder = os.path.join(BASE_DIR, 'import_data', 'resources')
for data_file in os.listdir(data_folder):
with open(os.path.join(data_folder, data_file), encoding='utf-8') as data_file:
data = json.loads(data_file.read())
for key, data_object in data.items():
UUID = data_object.get('UUID', None)
Name = data_object.get('Name', None)
IssuedNumber = data_object.get('IssuedNumber', None)
Capacity = data_object.get('Capacity', None)
Licensee = data_object.get('Licensee', None)
Email = data_object.get('Email', None)
AdministratorName = data_object.get('AdministratorName', None)
TelephoneNumber = data_object.get('TelephoneNumber', None)
ClosedTimestamp = data_object.get('ClosedTimestamp', None)
MostRecentLicenseTimestamp = data_object.get('MostRecentLicenseTimestamp', None)
PrimaryAddress = data_object["AddressInfo"]["PrimaryAddress"]
SecondaryAddress = data_object["AddressInfo"]["SecondaryAddress"]
City = data_object["AddressInfo"]["City"]
RegionOrState = data_object["AddressInfo"]["RegionOrState"]
PostalCode = data_object["AddressInfo"]["PostalCode"]
Geolocation = data_object["AddressInfo"]["Geolocation"]
ComplaintRelatedVisits = data_object["InspectionInfo"]["ComplaintRelatedVisits"]
InspectionRelatedVisits = data_object["InspectionInfo"]["InspectionRelatedVisits"]
NumberOfVisits = data_object["InspectionInfo"]["NumberOfVisits"]
LastVisitTimestamp = data_object["InspectionInfo"]["LastVisitTimestamp"]
ComplaintsTypeA = data_object["Complaints"]["ComplaintsTypeA"]
ComplaintsTypeB = data_object["Complaints"]["ComplaintsTypeB"]
SubstantiatedAllegations = data_object["Complaints"]["SubstantiatedAllegations"]
TotalAllegations = data_object["Complaints"]["TotalAllegations"]
LatestUpdateTimestamp = data_object.get('LatestUpdateTimestamp', None)
if Facility.objects.filter(LatestUpdateTimestamp=LatestUpdateTimestamp):
msg = "\n\nfacility exists and is up to date: {}\n{}".format(Name, str())
print(msg)
else:
print("UPDATE")
facility, facility_created = Facility.objects.update_or_create(UUID=UUID,
defaults={
'Name': Name,
'IssuedNumber': IssuedNumber,
'Capacity': Capacity,
'Licensee': Licensee,
'Email': Email,
'AdministratorName': AdministratorName,
'TelephoneNumber': TelephoneNumber,
'ClosedTimestamp': ClosedTimestamp,
'MostRecentLicenseTimestamp': MostRecentLicenseTimestamp,
'LatestUpdateTimestamp': LatestUpdateTimestamp
}
)
def handle(self, *args, **options):
"""
Call the function to import data
"""
self.import_facility_from_file()
The json i'm importing
{"00016ed7be4872a19d6e16afc98a7389b2bb324a2":
{"UUID":"00016ed7be4872a19d6e1ed6f36b647f3eb41cadedd2130b103a5851caebc26fbbbf24c2f1a64d2cf34ac4e03aaa30309816f58c397e6afc98a7389b2bb324a2","Name":"Test Facility","IssuedNumber":"123456","Licensee":"Test Licensee","Email":"test#example.com","AdministratorName":"Test Name","TelephoneNumber":"(123) 456-7890324879","ImporterLastModifiedTimestamp":"1362985200",
"AddressInfo":{"PrimaryAddress":"123 Fake Road","SecondaryAddress":"","City":"Testcity","RegionOrState":"TX","PostalCode":"12345","Geolocation":"00.0000,-00.0000"},"Capacity":100,"MostRecentLicenseTimestamp":1575180000,"ClosedTimestamp":0,
"InspectionInfo":{"ComplaintRelatedVisits":0,"InspectionRelatedVisits":0,"NumberOfVisits":0,"LastVisitTimestamp":0},
"Complaints":{"ComplaintsTypeA":0,"ComplaintsTypeB":0,"SubstantiatedAllegations":0,"TotalAllegations":0}},
"00016ed7be4872a15435435435b2bb324a2":
{"UUID":"000c93dcb7a0b3d5783bb330892aff6abdb9fb57a7d3701c2d903f3640877579f3173ecd8a80532f6c3d53dbacde78a6a54ae42fef321a5793f5a01934f8de7a","Name":"Test Facility 2","IssuedNumber":"123456","Licensee":"Test Licensee","Email":"test#example.com","AdministratorName":"Test Name","TelephoneNumber":"(123) 456-7890324879","ImporterLastModifiedTimestamp":"1362985200",
"AddressInfo":{"PrimaryAddress":"123 Fake Road","SecondaryAddress":"","City":"Testcity","RegionOrState":"TX","PostalCode":"12345","Geolocation":"00.0000,-00.0000"},"Capacity":100,"MostRecentLicenseTimestamp":1575180000,"ClosedTimestamp":0,
"InspectionInfo":{"ComplaintRelatedVisits":0,"InspectionRelatedVisits":0,"NumberOfVisits":0,"LastVisitTimestamp":0},
"Complaints":{"ComplaintsTypeA":0,"ComplaintsTypeB":0,"SubstantiatedAllegations":0,"TotalAllegations":0}},
"00234324324343243afc98a7389b2bb324a2":
{"UUID":"fffd4dec10054e6e1deb2a2266a7c6bb0136ba46222e734ceed5855651f735cfbe0bb66cfaf27c3d175ae261a8f6df0c36b5390d15c70b07d67e35e1081aaf6d","Name":"Test Facility 3","IssuedNumber":"123456","Licensee":"Test Licensee","Email":"test#example.com","AdministratorName":"Test Name","TelephoneNumber":"(123) 456-7890324879","ImporterLastModifiedTimestamp":"1362985200",
"AddressInfo":{"PrimaryAddress":"123 Fake Road","SecondaryAddress":"","City":"Testcity","RegionOrState":"TX","PostalCode":"12345","Geolocation":"00.0000,-00.0000"},"Capacity":100,"MostRecentLicenseTimestamp":1575180000,"ClosedTimestamp":0,
"InspectionInfo":{"ComplaintRelatedVisits":0,"InspectionRelatedVisits":0,"NumberOfVisits":0,"LastVisitTimestamp":0},
"Complaints":{"ComplaintsTypeA":0,"ComplaintsTypeB":0,"SubstantiatedAllegations":0,"TotalAllegations":0}}}
if Facility.objects.filter(ImporterLastModifiedTimestamp=ImporterLastModifiedTimestamp):
The if statement above is True as soon as you check it with a timestamp that is the same as one of the objects inserted before
You need to filter UUID and timestamp to catch the one single object you want to check if it has changed.

Is it possible to fetch many objects together from Google App Engine?

We have about 5,000 objects of class Domain in Google App Engine, and we want to export the list of domains to CSV. Each domain is linked to an object of class DomainStateData:
class DomainStateData(db.Expando, ExpandoEntity):
plan = db.ReferenceProperty(Plan)
plan_expiration = db.DateTimeProperty()
trial_expiration = db.DateTimeProperty()
date_created = db.DateTimeProperty(auto_now_add=True, indexed=True)
last_modified = db.DateTimeProperty(auto_now=True)
class Domain(db.Expando, ExpandoEntity, SocialIconsEntity):
"""
Domain Model
"""
domain = db.StringProperty(required=True)
...
_state_data = db.ReferenceProperty(DomainStateData)
#property
def state_data(self):
try:
if not self._state_data:
# try to get it, if not, build it
sd = DomainStateData.get_by_key_name(self.key().name())
if not sd:
sd = DomainStateData(key_name=self.key().name()).put()
self._state_data = sd
self.put()
return self._state_data
else:
return self._state_data
except ReferencePropertyResolveError:
self._state_data = DomainStateData(key_name=self.key().name()).put()
self.put()
return self._state_data
I wrote a code which exports 100 domains to CSV (it takes 5 seconds), but if I try to fetch all the 5,000 domains I get a timeout, which is 60 seconds. Is it possible to fetch all the DomainStateData objects together without a timeout? Here is my code that exports the domains to CSV:
import sys
sys.path.insert(0, 'libs')
import webapp2
import datetime
import csv
from models import Domain
class ExportAllDomainsToCsvHandler(webapp2.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/csv'
self.response.headers['Content-Disposition'] = 'attachment; filename="All Domains [{0}].csv"'.format(str(datetime.date.today()))
writer = csv.writer(self.response.out)
writer.writerow(["Domain", "Current state", "Plan expiration date", "Trial expiration date", "Current oauth user"])
all_domains = Domain.all().fetch(100)
all_domains.sort(key=lambda domain: (0 if domain.state_data.plan_expiration is None else 1, domain.state_data.plan_expiration, 0 if domain.state_data.trial_expiration is None else 1, domain.state_data.trial_expiration, domain.domain))
for domain in all_domains:
if (domain.state_data.plan_expiration is None):
domain_plan_expiration = "No plan expiration date"
else:
domain_plan_expiration = domain.state_data.plan_expiration.strftime('%Y-%m-%d')
if (domain.state_data.trial_expiration is None):
domain_trial_expiration = "No trial expiration date"
else:
domain_trial_expiration = domain.state_data.trial_expiration.strftime('%Y-%m-%d')
writer.writerow([domain.domain, domain.cur_state.name, domain_plan_expiration, domain_trial_expiration, domain.admin])
app = webapp2.WSGIApplication([
("/csv/export_all_domains_to_csv", ExportAllDomainsToCsvHandler)
], debug=True)
OK, I found a solution. I fetched all the DomainStateData objects directly from the database and now it takes 35 seconds to create the CSV with all the domains. Here is my code, I didn't change the models:
import sys
sys.path.insert(0, 'libs')
import webapp2
import datetime
import csv
from models import DomainStateData, Domain
class ExportAllDomainsToCsvHandler(webapp2.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/csv'
self.response.headers['Content-Disposition'] = 'attachment; filename="All Domains [{0}].csv"'.format(str(datetime.date.today()))
writer = csv.writer(self.response.out)
writer.writerow(["Domain", "Current state", "Plan expiration date", "Trial expiration date", "Current oauth user"])
all_domain_state_data_dict = dict()
all_domain_state_data = DomainStateData.all().fetch(1000000)
all_domains = Domain.all().fetch(1000000)
for domain_state_data in all_domain_state_data:
all_domain_state_data_dict[domain_state_data.key().name()] = domain_state_data
for domain in all_domains:
if (domain.key().name() in all_domain_state_data_dict):
domain.__state_data = all_domain_state_data_dict[domain.key().name()]
all_domains.sort(key=lambda domain: (0 if domain.__state_data.plan_expiration is None else 1, domain.__state_data.plan_expiration, 0 if domain.__state_data.trial_expiration is None else 1, domain.__state_data.trial_expiration, domain.domain))
for domain in all_domains:
if (domain.__state_data.plan_expiration is None):
domain_plan_expiration = "No plan expiration date"
else:
domain_plan_expiration = domain.__state_data.plan_expiration.strftime('%Y-%m-%d')
if (domain.__state_data.trial_expiration is None):
domain_trial_expiration = "No trial expiration date"
else:
domain_trial_expiration = domain.__state_data.trial_expiration.strftime('%Y-%m-%d')
writer.writerow([domain.domain, domain.cur_state.name, domain_plan_expiration, domain_trial_expiration, domain.admin])
app = webapp2.WSGIApplication([
("/csv/export_all_domains_to_csv", ExportAllDomainsToCsvHandler)
], debug=True)

Filling Livecycle form with Django

I am trying to fill a livecycle created form with form data from django. Now I think I have the code done correctly but I am having a hard time with the structure of the livecycle form. Currently I have the ability to populate pdf's created with adobe acrobat but not livecycle. Is there a certain file structure for livecycle?
Here is the function I call to fill the pdf:
def print_rdba(client=None, data=None, investment_form=None):
from django.http import HttpResponse
from clients.models import Client
from dateutil.parser import parse
from settings import URL
from datetime import date
file = ''
print data
fdf = '<?xml version="1.0" encoding="UTF-8"?>\n<xfdf xmlns="http://ns.adobe.com/xfdf/" xml:space="preserve">\n\t<fields>'
fdf += fdf_val_str("primary1_lastname", data.get('lastname'))
fdf += fdf_val_str("primary1_firstname", data.get('firstname'))
if investment_form:
file = "%s%s" % (URL, investment_form.file.url)
fdf += '''</fields>
<f href="%s" target="_blank"/>
</xfdf>''' % file
fdf = fdf.replace('^M', '')
response = HttpResponse(fdf.encode("ISO-8859-1"), mimetype='application/pdf')
response['Content-Disposition'] = 'attachment; filename=form.xfdf'
return response
Here is fdf_val_str:
def fdf_val_str(field, val):
val = str(val).replace('&','&')
return '<field name="%s"><value>%s</value></field>\n' % (field, val)
My clients edit function in my views.py:
#login_required
#user_passes_test(lambda u: u.is_staff or u.rep_set.get().add_clients, login_url='/')
def edit(request, client=None, *args, **kwargs):
from clients.forms import ClientForm
from entity.forms import LocationForm
from investments.models import InvestmentForm
from lib.tools import print_rdba
...
rdba_btn = InvestmentForm.objects.get(id=3)
context = {}
...
if request.POST.has_key('submit-%s' % rdba_btn.code):
request.user.message_set.create(message='Generating PDF form')
return print_rdba(client=client, data=form.data, investment_form=rdba_btn)
Any help would be much appreciated
Do you have LiveCycle Forms installed? You could then generate the XML data with DJango and sending it to LiveCycle to render the PDF Form
edit:
And you should notice LiveCycle Designer generates XFA-based forms, which differ from XFDF

How to add OAuth 2.0 providers?

I could reproduce my bug using servside OAuth2.0 only so it's not javascript and the issue is that I must reload to make login / logout take effect and I want it to work without javascript. I have an idea that making logout twice makes logout effective so I could use a custom request handler for /login and/or /logour or just /sessionchange that will do a self.redirect but it's not the clean solution. Maybe you can take a look at the code and see why I must logout twice ie I must reload and can I workaround this using a self.redirect ? Am I using cookies the right way, the new cookie, or do I get it mixed up? I'm doing this both for the website and for the FB app. I'll be glad if you can come with any suggestion. There's a background of 2 related questions from before I removed the Javascript. And BTW should I use class Facebook or facebook.py? I think I commented out where the old cookie is set and that this will be correct once OAuth 2.0 handles my authentication serverside. Can you comment or answer? Thank you in advance if you can review and comment.
How to make my welcome text appear?
How to make this page reload on login / logout?
Why my strange results rendering the user object?
login.html
{% load i18n %}
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head> <title>{% trans "Log in" %}</title>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', '{{analytics}}']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '164355773607006', // App ID
channelURL : '//WWW.KOOLBUSINESS.COM/static/channel.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
oauth : true, // enable OAuth 2.0
xfbml : true // parse XFBML
});
// Additional initialization code here
};
// Load the SDK Asynchronously
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
</script>
<img src="/_/img/loginwithfacebook.png">
<img src="/_/img/loginwithgoogle.png"><br>{% if user %}Logout Google{% endif %}
{% if current_user %}Logout Facebook {% endif %}
{% if current_user %}Logout Facebook JS {% endif %}
</body>
</html>
class BaseHandler(webapp.RequestHandler):
facebook = None
user = None
csrf_protect = True
#property
def current_user(self):
if not hasattr(self, "_current_user"):
self._current_user = None
cookie = facebook.get_user_from_cookie(
self.request.cookies, facebookconf.FACEBOOK_APP_ID, facebookconf.FACEBOOK_APP_SECRET)
logging.debug("logging cookie"+str(cookie))
if cookie:
# Store a local instance of the user data so we don't need
# a round-trip to Facebook on every request
user = FBUser.get_by_key_name(cookie["uid"])
logging.debug("user "+str(user))
logging.debug("username "+str(user.name))
if not user:
graph = facebook.GraphAPI(cookie["access_token"])
profile = graph.get_object("me")
user = FBUser(key_name=str(profile["id"]),
id=str(profile["id"]),
name=profile["name"],
profile_url=profile["link"],
access_token=cookie["access_token"])
user.put()
elif user.access_token != cookie["access_token"]:
user.access_token = cookie["access_token"]
user.put()
self._current_user = user
return self._current_user
def initialize(self, request, response):
"""General initialization for every request"""
super(BaseHandler, self).initialize(request, response)
try:
self.init_facebook()
self.init_csrf()
self.response.headers[u'P3P'] = u'CP=HONK' # iframe cookies in IE
except Exception, ex:
self.log_exception(ex)
raise
def handle_exception(self, ex, debug_mode):
"""Invoked for unhandled exceptions by webapp"""
self.log_exception(ex)
self.render(u'error',
trace=traceback.format_exc(), debug_mode=debug_mode)
def log_exception(self, ex):
"""Internal logging handler to reduce some App Engine noise in errors"""
msg = ((str(ex) or ex.__class__.__name__) +
u': \n' + traceback.format_exc())
if isinstance(ex, urlfetch.DownloadError) or \
isinstance(ex, DeadlineExceededError) or \
isinstance(ex, CsrfException) or \
isinstance(ex, taskqueue.TransientError):
logging.warn(msg)
else:
logging.error(msg)
def set_cookie(self, name, value, expires=None):
if value is None:
value = 'deleted'
expires = datetime.timedelta(minutes=-50000)
jar = Cookie.SimpleCookie()
jar[name] = value
jar[name]['path'] = u'/'
if expires:
if isinstance(expires, datetime.timedelta):
expires = datetime.datetime.now() + expires
if isinstance(expires, datetime.datetime):
expires = expires.strftime('%a, %d %b %Y %H:%M:%S')
jar[name]['expires'] = expires
self.response.headers.add_header(*jar.output().split(u': ', 1))
def render(self, name, **data):
"""Render a template"""
if not data:
data = {}
data[u'js_conf'] = json.dumps({
u'appId': facebookconf.FACEBOOK_APP_ID,
u'canvasName': facebookconf.FACEBOOK_CANVAS_NAME,
u'userIdOnServer': self.user.id if self.user else None,
})
data[u'logged_in_user'] = self.user
data[u'message'] = self.get_message()
data[u'csrf_token'] = self.csrf_token
data[u'canvas_name'] = facebookconf.FACEBOOK_CANVAS_NAME
data[u'current_user']=self.current_user
data[u'user']=users.get_current_user()
data[u'facebook_app_id']=facebookconf.FACEBOOK_APP_ID
user = users.get_current_user()
data[u'logout_url']=users.create_logout_url(self.request.uri) if users.get_current_user() else 'https://www.facebook.com/dialog/oauth?client_id=164355773607006&redirect_uri='+self.request.uri
host=os.environ.get('HTTP_HOST', os.environ['SERVER_NAME'])
data[u'host']=host
if host.find('.br') > 0:
logo = 'Montao.com.br'
logo_url = '/_/img/montao_small.gif'
analytics = 'UA-637933-12'
domain = None
else:
logo = 'Koolbusiness.com'
logo_url = '/_/img/kool_business.png'
analytics = 'UA-3492973-18'
domain = 'koolbusiness'
data[u'domain']=domain
data[u'analytics']=analytics
data[u'logo']=logo
data[u'logo_url']=logo_url
data[u'admin']=users.is_current_user_admin()
if user:
data[u'greeting'] = ("Welcome, %s! (sign out)" %
(user.nickname(), users.create_logout_url("/")))
self.response.out.write(template.render(
os.path.join(
os.path.dirname(__file__), 'templates', name + '.html'),
data))
def init_facebook(self):
facebook = Facebook()
user = None
# initial facebook request comes in as a POST with a signed_request
if u'signed_request' in self.request.POST:
facebook.load_signed_request(self.request.get('signed_request'))
# we reset the method to GET because a request from facebook with a
# signed_request uses POST for security reasons, despite it
# actually being a GET. in webapp causes loss of request.POST data.
self.request.method = u'GET'
#self.set_cookie(
#'u', facebook.user_cookie, datetime.timedelta(minutes=1440))
elif 'u' in self.request.cookies:
facebook.load_signed_request(self.request.cookies.get('u'))
# try to load or create a user object
if facebook.user_id:
user = FBUser.get_by_key_name(facebook.user_id)
if user:
# update stored access_token
if facebook.access_token and \
facebook.access_token != user.access_token:
user.access_token = facebook.access_token
user.put()
# refresh data if we failed in doing so after a realtime ping
if user.dirty:
user.refresh_data()
# restore stored access_token if necessary
if not facebook.access_token:
facebook.access_token = user.access_token
if not user and facebook.access_token:
me = facebook.api(u'/me', {u'fields': _USER_FIELDS})
try:
friends = [user[u'id'] for user in me[u'friends'][u'data']]
user = FBUser(key_name=facebook.user_id,
id=facebook.user_id, friends=friends,
access_token=facebook.access_token, name=me[u'name'],
email=me.get(u'email'), picture=me[u'picture'])
user.put()
except KeyError, ex:
pass # ignore if can't get the minimum fields
self.facebook = facebook
self.user = user
def init_csrf(self):
"""Issue and handle CSRF token as necessary"""
self.csrf_token = self.request.cookies.get(u'c')
if not self.csrf_token:
self.csrf_token = str(uuid4())[:8]
self.set_cookie('c', self.csrf_token)
if self.request.method == u'POST' and self.csrf_protect and \
self.csrf_token != self.request.POST.get(u'_csrf_token'):
raise CsrfException(u'Missing or invalid CSRF token.')
def set_message(self, **obj):
"""Simple message support"""
self.set_cookie('m', base64.b64encode(json.dumps(obj)) if obj else None)
def get_message(self):
"""Get and clear the current message"""
message = self.request.cookies.get(u'm')
if message:
self.set_message() # clear the current cookie
return json.loads(base64.b64decode(message))
class Facebook(object):
"""Wraps the Facebook specific logic"""
def __init__(self, app_id=facebookconf.FACEBOOK_APP_ID,
app_secret=facebookconf.FACEBOOK_APP_SECRET):
self.app_id = app_id
self.app_secret = app_secret
self.user_id = None
self.access_token = None
self.signed_request = {}
def api(self, path, params=None, method=u'GET', domain=u'graph'):
"""Make API calls"""
if not params:
params = {}
params[u'method'] = method
if u'access_token' not in params and self.access_token:
params[u'access_token'] = self.access_token
result = json.loads(urlfetch.fetch(
url=u'https://' + domain + u'.facebook.com' + path,
payload=urllib.urlencode(params),
method=urlfetch.POST,
headers={
u'Content-Type': u'application/x-www-form-urlencoded'})
.content)
if isinstance(result, dict) and u'error' in result:
raise FacebookApiError(result)
return result
def load_signed_request(self, signed_request):
"""Load the user state from a signed_request value"""
try:
sig, payload = signed_request.split(u'.', 1)
sig = self.base64_url_decode(sig)
data = json.loads(self.base64_url_decode(payload))
expected_sig = hmac.new(
self.app_secret, msg=payload, digestmod=hashlib.sha256).digest()
# allow the signed_request to function for upto 1 day
if sig == expected_sig and \
data[u'issued_at'] > (time.time() - 86400):
self.signed_request = data
self.user_id = data.get(u'user_id')
self.access_token = data.get(u'oauth_token')
except ValueError, ex:
pass # ignore if can't split on dot
#property
def user_cookie(self):
"""Generate a signed_request value based on current state"""
if not self.user_id:
return
payload = self.base64_url_encode(json.dumps({
u'user_id': self.user_id,
u'issued_at': str(int(time.time())),
}))
sig = self.base64_url_encode(hmac.new(
self.app_secret, msg=payload, digestmod=hashlib.sha256).digest())
return sig + '.' + payload
#staticmethod
def base64_url_decode(data):
data = data.encode(u'ascii')
data += '=' * (4 - (len(data) % 4))
return base64.urlsafe_b64decode(data)
#staticmethod
def base64_url_encode(data):
return base64.urlsafe_b64encode(data).rstrip('=')
facebook.py
#!/usr/bin/env python
#
# Copyright 2010 Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Python client library for the Facebook Platform.
This client library is designed to support the Graph API and the official
Facebook JavaScript SDK, which is the canonical way to implement
Facebook authentication. Read more about the Graph API at
http://developers.facebook.com/docs/api. You can download the Facebook
JavaScript SDK at http://github.com/facebook/connect-js/.
If your application is using Google AppEngine's webapp framework, your
usage of this module might look like this:
user = facebook.get_user_from_cookie(self.request.cookies, key, secret)
if user:
graph = facebook.GraphAPI(user["access_token"])
profile = graph.get_object("me")
friends = graph.get_connections("me", "friends")
"""
from google.appengine.dist import use_library
use_library('django', '1.2')
import cgi
import hashlib
import time
import urllib
#from django.utils import translation, simplejson as json
# Find a JSON parser
try:
# For Google AppEngine
from django.utils import simplejson
_parse_json = lambda s: simplejson.loads(s)
except ImportError:
try:
import simplejson
_parse_json = lambda s: simplejson.loads(s)
except ImportError:
import json
_parse_json = lambda s: json.loads(s)
class GraphAPI(object):
"""A client for the Facebook Graph API.
See http://developers.facebook.com/docs/api for complete documentation
for the API.
The Graph API is made up of the objects in Facebook (e.g., people, pages,
events, photos) and the connections between them (e.g., friends,
photo tags, and event RSVPs). This client provides access to those
primitive types in a generic way. For example, given an OAuth access
token, this will fetch the profile of the active user and the list
of the user's friends:
graph = facebook.GraphAPI(access_token)
user = graph.get_object("me")
friends = graph.get_connections(user["id"], "friends")
You can see a list of all of the objects and connections supported
by the API at http://developers.facebook.com/docs/reference/api/.
You can obtain an access token via OAuth or by using the Facebook
JavaScript SDK. See http://developers.facebook.com/docs/authentication/
for details.
If you are using the JavaScript SDK, you can use the
get_user_from_cookie() method below to get the OAuth access token
for the active user from the cookie saved by the SDK.
"""
def __init__(self, access_token=None):
self.access_token = access_token
def get_object(self, id, **args):
"""Fetchs the given object from the graph."""
return self.request(id, args)
def get_objects(self, ids, **args):
"""Fetchs all of the given object from the graph.
We return a map from ID to object. If any of the IDs are invalid,
we raise an exception.
"""
args["ids"] = ",".join(ids)
return self.request("", args)
def get_connections(self, id, connection_name, **args):
"""Fetchs the connections for given object."""
return self.request(id + "/" + connection_name, args)
def put_object(self, parent_object, connection_name, **data):
"""Writes the given object to the graph, connected to the given parent.
For example,
graph.put_object("me", "feed", message="Hello, world")
writes "Hello, world" to the active user's wall. Likewise, this
will comment on a the first post of the active user's feed:
feed = graph.get_connections("me", "feed")
post = feed["data"][0]
graph.put_object(post["id"], "comments", message="First!")
See http://developers.facebook.com/docs/api#publishing for all of
the supported writeable objects.
Most write operations require extended permissions. For example,
publishing wall posts requires the "publish_stream" permission. See
http://developers.facebook.com/docs/authentication/ for details about
extended permissions.
"""
assert self.access_token, "Write operations require an access token"
return self.request(parent_object + "/" + connection_name, post_args=data)
def put_wall_post(self, message, attachment={}, profile_id="me"):
"""Writes a wall post to the given profile's wall.
We default to writing to the authenticated user's wall if no
profile_id is specified.
attachment adds a structured attachment to the status message being
posted to the Wall. It should be a dictionary of the form:
{"name": "Link name"
"link": "http://www.example.com/",
"caption": "{*actor*} posted a new review",
"description": "This is a longer description of the attachment",
"picture": "http://www.example.com/thumbnail.jpg"}
"""
return self.put_object(profile_id, "feed", message=message, **attachment)
def put_comment(self, object_id, message):
"""Writes the given comment on the given post."""
return self.put_object(object_id, "comments", message=message)
def put_like(self, object_id):
"""Likes the given post."""
return self.put_object(object_id, "likes")
def delete_object(self, id):
"""Deletes the object with the given ID from the graph."""
self.request(id, post_args={"method": "delete"})
def request(self, path, args=None, post_args=None):
"""Fetches the given path in the Graph API.
We translate args to a valid query string. If post_args is given,
we send a POST request to the given path with the given arguments.
"""
if not args: args = {}
if self.access_token:
if post_args is not None:
post_args["access_token"] = self.access_token
else:
args["access_token"] = self.access_token
post_data = None if post_args is None else urllib.urlencode(post_args)
file = urllib.urlopen("https://graph.facebook.com/" + path + "?" +
urllib.urlencode(args), post_data)
try:
response = _parse_json(file.read())
finally:
file.close()
if response.get("error"):
raise GraphAPIError(response["error"]["type"],
response["error"]["message"])
return response
class GraphAPIError(Exception):
def __init__(self, type, message):
Exception.__init__(self, message)
self.type = type
##### NEXT TWO FUNCTIONS PULLED FROM https://github.com/jgorset/facepy/blob/master/facepy/signed_request.py
import base64
import hmac
def urlsafe_b64decode(str):
"""Perform Base 64 decoding for strings with missing padding."""
l = len(str)
pl = l % 4
return base64.urlsafe_b64decode(str.ljust(l+pl, "="))
def parse_signed_request(signed_request, secret):
"""
Parse signed_request given by Facebook (usually via POST),
decrypt with app secret.
Arguments:
signed_request -- Facebook's signed request given through POST
secret -- Application's app_secret required to decrpyt signed_request
"""
if "." in signed_request:
esig, payload = signed_request.split(".")
else:
return {}
sig = urlsafe_b64decode(str(esig))
data = _parse_json(urlsafe_b64decode(str(payload)))
if not isinstance(data, dict):
raise SignedRequestError("Pyload is not a json string!")
return {}
if data["algorithm"].upper() == "HMAC-SHA256":
if hmac.new(secret, payload, hashlib.sha256).digest() == sig:
return data
else:
raise SignedRequestError("Not HMAC-SHA256 encrypted!")
return {}
def get_user_from_cookie(cookies, app_id, app_secret):
"""Parses the cookie set by the official Facebook JavaScript SDK.
cookies should be a dictionary-like object mapping cookie names to
cookie values.
If the user is logged in via Facebook, we return a dictionary with the
keys "uid" and "access_token". The former is the user's Facebook ID,
and the latter can be used to make authenticated requests to the Graph API.
If the user is not logged in, we return None.
Download the official Facebook JavaScript SDK at
http://github.com/facebook/connect-js/. Read more about Facebook
authentication at http://developers.facebook.com/docs/authentication/.
"""
cookie = cookies.get("fbsr_" + app_id, "")
if not cookie:
return None
response = parse_signed_request(cookie, app_secret)
if not response:
return None
args = dict(
code = response['code'],
client_id = app_id,
client_secret = app_secret,
redirect_uri = '',
)
file = urllib.urlopen("https://graph.facebook.com/oauth/access_token?" + urllib.urlencode(args))
try:
token_response = file.read()
finally:
file.close()
access_token = cgi.parse_qs(token_response)["access_token"][-1]
return dict(
uid = response["user_id"],
access_token = access_token,
)
Some log traces are
2011-10-18 18:25:07.912
logging cookie{'access_token': 'AAACVewZBArF4BACUDwnDap5OrQQ5dx0sHEKuPJkIJJ8GdXlYdni5K50xKw6s8BSIDZCpKBtVWF9maHMoJeF9ZCRRYM1zgZD', 'uid': u'32740016'}
D 2011-10-18 18:25:07.925
user <__main__.FBUser object at 0x39d606ae980b528>
D 2011-10-18 18:25:07.925
username Niklas R
Now looking at the code that does this it seems to me that I'm confusing the module facebook with the variable facebook where one is the class facebook from the example project and one is the new recommended module facebook.py:
class BaseHandler(webapp.RequestHandler):
facebook = None
user = None
csrf_protect = True
#property
def current_user(self):
if not hasattr(self, "_current_user"):
self._current_user = None
cookie = facebook.get_user_from_cookie(
self.request.cookies, facebookconf.FACEBOOK_APP_ID, facebookconf.FACEBOOK_APP_SECRET)
logging.debug("logging cookie"+str(cookie))
if cookie:
# Store a local instance of the user data so we don't need
# a round-trip to Facebook on every request
user = FBUser.get_by_key_name(cookie["uid"])
logging.debug("user "+str(user))
logging.debug("username "+str(user.name))
if not user:
graph = facebook.GraphAPI(cookie["access_token"])
profile = graph.get_object("me")
user = FBUser(key_name=str(profile["id"]),
id=str(profile["id"]),
name=profile["name"],
profile_url=profile["link"],
access_token=cookie["access_token"])
user.put()
elif user.access_token != cookie["access_token"]:
user.access_token = cookie["access_token"]
user.put()
self._current_user = user
return self._current_user
How to add Facebook as OAuth 2.0 provider: Here's how I make "Login with facebook" for my website with OAuth instead of javascript / cookie this is python only for OAuth 2.0 with Facebook and as far as I can tell it's working:
class FBUser(db.Model):
id = db.StringProperty(required=True)
created = db.DateTimeProperty(auto_now_add=True)
updated = db.DateTimeProperty(auto_now=True)
name = db.StringProperty(required=True)
profile_url = db.StringProperty()
access_token = db.StringProperty(required=True)
name = db.StringProperty(required=True)
picture = db.StringProperty()
email = db.StringProperty()
friends = db.StringListProperty()
class I18NPage(I18NHandler):
def get(self):
if self.request.get('code'):
args = dict(
code = self.request.get('code'),
client_id = facebookconf.FACEBOOK_APP_ID,
client_secret = facebookconf.FACEBOOK_APP_SECRET,
redirect_uri = 'http://www.koolbusiness.com/',
)
logging.debug("client_id"+str(args))
file = urllib.urlopen("https://graph.facebook.com/oauth/access_token?" + urllib.urlencode(args))
try:
logging.debug("reading file")
token_response = file.read()
logging.debug("read file"+str(token_response))
finally:
file.close()
access_token = cgi.parse_qs(token_response)["access_token"][-1]
graph = main.GraphAPI(access_token)
user = graph.get_object("me") #write the access_token to the datastore
fbuser = main.FBUser.get_by_key_name(user["id"])
logging.debug("fbuser "+str(fbuser))
if not fbuser:
fbuser = main.FBUser(key_name=str(user["id"]),
id=str(user["id"]),
name=user["name"],
profile_url=user["link"],
access_token=access_token)
fbuser.put()
elif fbuser.access_token != access_token:
fbuser.access_token = access_token
fbuser.put()
The login link is
<img src="/_/img/loginwithfacebook.png"> that redirects and allows me to pick up the access_token in the method above and logout is straightforward:
{% trans "Log out" %}

Categories