diff --git a/js/legacy/widgets/form/form.js b/js/legacy/widgets/form/form.js
index b2eaefdf45..ed90f44621 100644
--- a/js/legacy/widgets/form/form.js
+++ b/js/legacy/widgets/form/form.js
@@ -1095,6 +1095,8 @@ _f.get_value = function(dt, dn, fn) {
_f.Frm.prototype.set_value_in_locals = function(dt, dn, fn, v) {
var d = locals[dt][dn];
+ if (!d) return;
+
var changed = d[fn] != v;
if(changed && (d[fn]==null || v==null) && (cstr(d[fn])==cstr(v)))
changed = false;
diff --git a/py/webnotes/auth.py b/py/webnotes/auth.py
index 237cc0f0fa..16cec650df 100644
--- a/py/webnotes/auth.py
+++ b/py/webnotes/auth.py
@@ -236,25 +236,35 @@ class CookieManager:
webnotes.incoming_cookies = cookies
def set_cookies(self):
- if webnotes.session.get('sid'):
- webnotes.cookies['sid'] = webnotes.session['sid']
+ if not webnotes.session.get('sid'): return
+
+ from webnotes.utils import get_encoded_string
+ import datetime
- # sid expires in 3 days
- import datetime
- expires = datetime.datetime.now() + datetime.timedelta(days=3)
- webnotes.cookies['sid']['expires'] = expires.strftime('%a, %d %b %Y %H:%M:%S')
- webnotes.cookies['sid']['path'] = '/'
+ # sid expires in 3 days
+ expires = datetime.datetime.now() + datetime.timedelta(days=3)
+ expires = expires.strftime('%a, %d %b %Y %H:%M:%S')
+
+ webnotes.cookies[b'sid'] = get_encoded_string(webnotes.session['sid'])
+ webnotes.cookies[b'sid'][b'expires'] = get_encoded_string(expires)
+ webnotes.cookies[b'sid'][b'path'] = b'/'
def set_remember_me(self):
- if webnotes.utils.cint(webnotes.form_dict.get('remember_me')):
- remember_days = webnotes.conn.get_value('Control Panel',None,'remember_for_days') or 7
- webnotes.cookies['remember_me'] = 1
+ from webnotes.utils import cint, get_encoded_string
+
+ if not cint(webnotes.form_dict.get('remember_me')): return
+
+ remember_days = webnotes.conn.get_value('Control Panel', None,
+ 'remember_for_days') or 7
+
+ import datetime
+ expires = datetime.datetime.now() + \
+ datetime.timedelta(days=remember_days)
+ expires = expires.strftime('%a, %d %b %Y %H:%M:%S')
- import datetime
- expires = datetime.datetime.now() + datetime.timedelta(days=remember_days)
-
- for k in webnotes.cookies.keys():
- webnotes.cookies[k]['expires'] = expires.strftime('%a, %d %b %Y %H:%M:%S')
+ webnotes.cookies[b'remember_me'] = 1
+ for k in webnotes.cookies.keys():
+ webnotes.cookies[k][b'expires'] = get_encoded_string(expires)
# =================================================================================
# Session
diff --git a/py/webnotes/db.py b/py/webnotes/db.py
index 44d2a05a11..527934385f 100644
--- a/py/webnotes/db.py
+++ b/py/webnotes/db.py
@@ -270,6 +270,8 @@ class Database:
if type(fieldname) in (list, tuple):
fl = '`, `'.join(fieldname)
try:
+ import json
+ from webnotes.utils import cstr
r = self.sql("select `%s` from `tab%s` where name='%s'" % (fl, doctype, docname))
except Exception, e:
if e.args[0]==1054 and ignore:
diff --git a/py/webnotes/handler.py b/py/webnotes/handler.py
index 91aac993fe..bb43407e52 100755
--- a/py/webnotes/handler.py
+++ b/py/webnotes/handler.py
@@ -91,10 +91,9 @@ def dt_map():
@webnotes.whitelist()
def load_month_events():
import webnotes
- form = webnotes.form
- mm = form.getvalue('month')
- yy = form.getvalue('year')
+ mm = webnotes.form_dict.get('month')
+ yy = webnotes.form_dict.get('year')
m_st = str(yy) + '-' + str(mm) + '-01'
m_end = str(yy) + '-' + str(mm) + '-31'
@@ -107,11 +106,10 @@ def load_month_events():
@webnotes.whitelist()
def import_csv():
import webnotes.model.import_docs
- form = webnotes.form
from webnotes.utils import cint
i = webnotes.model.import_docs.CSVImport()
- r = i.import_csv(form.getvalue('csv_file'), form.getvalue('dateformat'), form_dict.get('overwrite', 0) and 1)
+ r = i.import_csv(webnotes.form_dict.get('csv_file'), webnotes.form_dict.get('dateformat'), webnotes.form_dict.get('overwrite', 0) and 1)
webnotes.response['type']='iframe'
rhead = ''''''
@@ -233,8 +231,13 @@ def execute_cmd(cmd):
def get_method(cmd):
"""get method object from cmd"""
if '.' in cmd:
- module = __import__('.'.join(cmd.split('.')[:-1]), fromlist=[''])
- method = getattr(module, cmd.split('.')[-1])
+ from webnotes.utils import get_encoded_string
+ cmd_parts = cmd.split('.')
+ module_string = ".".join(cmd_parts[:-1])
+ method_string = cmd_parts[-1]
+ module = __import__(module_string,
+ fromlist=[get_encoded_string(method_string)])
+ method = getattr(module, method_string)
else:
method = globals()[cmd]
return method
@@ -251,71 +254,123 @@ def validate_cmd(cmd):
raise Exception, 'Cannot call database connection method directly from the handler'
def print_response():
- import string
- import os
+ print_map = {
+ 'csv': print_csv,
+ 'iframe': print_iframe,
+ 'download': print_raw,
+ 'json': print_json,
+ }
+
+ print_map.get(webnotes.response.get('type'), print_json)()
- if webnotes.response.get('type')=='csv':
- print_csv()
- elif webnotes.response.get('type')=='iframe':
- print_iframe()
- elif webnotes.response.get('type')=='download':
- print_raw()
- else:
- print_json()
-
-def print_csv():
- print "Content-Type: text/csv"
- print "Content-Disposition: attachment; filename="+webnotes.response['doctype'].replace(' ', '_')+".csv"
- print
- print webnotes.response['result']
-
-def print_iframe():
- import json
- print "Content-Type: text/html"
- print
- if webnotes.response.get('result'):
- print webnotes.response['result']
- if webnotes.debug_log:
- print """
- """ % (json.dumps(webnotes.message_log), json.dumps(webnotes.debug_log))
-
-def print_raw():
- import mimetypes
- print "Content-Type: %s" % (mimetypes.guess_type(webnotes.response['filename'])[0] or 'application/unknown')
- print "Content-Disposition: filename="+webnotes.response['filename'].replace(' ', '_')
- print
- print webnotes.response['filecontent']
+def print_content(content, args=None):
+ """encode and print content"""
+ if not args: args = {}
+
+ from webnotes.utils import get_encoded_string
+ print get_encoded_string("\n".join(content) % args)
def print_json():
make_logs()
cleanup_docs()
import json
- str_out = json.dumps(webnotes.response)
+ response = json.dumps(webnotes.response)
- if accept_gzip() and len(str_out)>512:
- out_buf = compressBuf(str_out)
- print "Content-Encoding: gzip"
- print "Content-Length: %d" % (len(out_buf))
- str_out = out_buf
+ content = []
+
+ if accept_gzip() and len(response)>512:
+ out_buf = compressBuf(response)
+ content += [
+ "Content-Encoding: gzip",
+ "Content-Length: %d" % (len(out_buf))
+ ]
+ response = out_buf
- print "Content-Type: text/html; charset: utf-8"
- print_cookies()
+ add_cookies()
+
+ content += [
+ "Content-Type: text/html; charset: utf-8",
+ "%(cookies)s",
+ "",
+ "%(response)s"
+ ]
+
+ args = {
+ 'cookies': webnotes.cookies,
+ 'response': response,
+ }
+
+ print_content(content, args)
+
+def print_csv():
+ content = [
+ "Content-Type: text/csv",
+ "Content-Disposition: attachment; filename=%(filename)s.csv",
+ "",
+ "%(response)s"
+ ]
+
+ args = {
+ "filename": webnotes.response['doctype'].replace(' ', '_'),
+ "response": webnotes.response['result'],
+ }
- # Headers end
- print
- print str_out
+ print_content(content, args)
+
+def print_iframe():
+ content = [
+ "Content-Type: text/html",
+ "",
+ "%(response)s",
+ "%(debug)s"
+ ]
+
+ args = {
+ 'response': webnotes.response.get('result') or '',
+ 'debug': ''
+ }
+
+ if webnotes.debug_log:
+ import json
+ args['debug'] = """\
+ """ % {
+ 'messages': json.dumps(webnotes.message_log).replace("'", "\\'"),
+ 'errors': json.dumps(webnotes.debug_log).replace("'", "\\'"),
+ }
+
+ print_content(content, args)
+
+def print_raw():
+ content = [
+ "Content-Type: %(mime_type)s",
+ "Content-Disposition: filename=%(filename)s",
+ "",
+ "%(response)s",
+ ]
+
+ import mimetypes
+ args = {
+ "mime_type": mimetypes.guess_type(webnotes.response['filename'])[0] \
+ or 'application/unknown',
+ "filename": webnotes.response['filename'].replace(' ', '_'),
+ "content": webnotes.response['filecontent'],
+ }
+
+ print_content(content, args)
def accept_gzip():
"""return true if client accepts gzip"""
@@ -333,15 +388,15 @@ def make_logs():
if webnotes.message_log:
t = '\n----------------\n'.join(webnotes.message_log)
- webnotes.response['server_messages'] = t
+ webnotes.response['server_messages'] = t
-def print_cookies():
+def add_cookies():
"""if there ar additional cookies defined during the request, add them"""
- if webnotes.cookies or webnotes.add_cookies:
+ from webnotes.utils import get_encoded_string
+ if webnotes.cookies or webnotes.add_cookies:
for c in webnotes.add_cookies.keys():
- webnotes.cookies[c] = webnotes.add_cookies[c]
-
- print webnotes.cookies
+ webnotes.cookies[get_encoded_string(c)] = \
+ get_encoded_string(webnotes.add_cookies[c])
def compressBuf(buf):
import gzip, cStringIO
diff --git a/py/webnotes/model/import_docs.py b/py/webnotes/model/import_docs.py
index a1d44dbbb1..e4b285839e 100644
--- a/py/webnotes/model/import_docs.py
+++ b/py/webnotes/model/import_docs.py
@@ -405,11 +405,10 @@ def get_template():
from webnotes.utils import getCSVelement
- form = webnotes.form
sql = webnotes.conn.sql
# get form values
- dt = form.getvalue('dt')
- overwrite = cint(form.getvalue('overwrite')) or 0
+ dt = webnotes.form_dict.get('dt')
+ overwrite = cint(webnotes.form_dict.get('overwrite')) or 0
pt, pf = '', ''
tmp_lbl, tmp_ml = [],[]
diff --git a/py/webnotes/profile.py b/py/webnotes/profile.py
index a2e88551be..40033d3e06 100644
--- a/py/webnotes/profile.py
+++ b/py/webnotes/profile.py
@@ -276,11 +276,11 @@ class Profile:
@webnotes.whitelist()
def get_user_img():
- if not webnotes.form.getvalue('username'):
+ if not webnotes.form_dict.get('username'):
webnotes.response['message'] = 'no_img_m'
return
- f = webnotes.conn.sql("select file_list from tabProfile where name=%s", webnotes.form.getvalue('username',''))
+ f = webnotes.conn.sql("select file_list from tabProfile where name=%s", webnotes.form_dict.get('username',''))
if f:
if f[0][0]:
lst = f[0][0].split('\n')
diff --git a/py/webnotes/utils/__init__.py b/py/webnotes/utils/__init__.py
index d1635964b7..ddc7a768a8 100644
--- a/py/webnotes/utils/__init__.py
+++ b/py/webnotes/utils/__init__.py
@@ -332,16 +332,49 @@ def cint(s):
except: tmp = 0
return tmp
-def cstr(s):
- """
- Convert to string
- """
- if isinstance(s, basestring):
- return s
- elif s==None:
- return ''
+def get_encoded_string(content, encoding='utf-8'):
+ content = convert_to_unicode(content)
+
+ if isinstance(content, str):
+ return content
+
else:
- return str(s)
+ return content.encode('utf-8')
+
+def get_string(content, encoding='utf-8', errors='ignore'):
+ content = convert_to_unicode(content)
+
+ if isinstance(content, unicode):
+ return content
+
+ else:
+ return unicode(content, encoding, errors)
+
+
+def convert_to_unicode(content):
+ """
+ converts types other than basestring to unicode
+ (like int, float, list, dict, etc.)
+ """
+ if content == None:
+ return ''
+ elif not isinstance(content, basestring):
+ return unicode(content)
+ else:
+ return content
+
+cstr = get_string
+
+# def cstr(s):
+# """
+# Convert to string
+# """
+# if isinstance(s, basestring):
+# return s
+# elif s==None:
+# return ''
+# else:
+# return str(s)
def str_esc_quote(s):
"""
diff --git a/py/webnotes/utils/email_lib/__init__.py b/py/webnotes/utils/email_lib/__init__.py
index ab9833182c..aad1bf3159 100644
--- a/py/webnotes/utils/email_lib/__init__.py
+++ b/py/webnotes/utils/email_lib/__init__.py
@@ -70,18 +70,14 @@ def sendmail(recipients, sender='', msg='', subject='[No Subject]', txt=None, \
footer = get_footer()
- # encode using utf-8
- footer = footer.encode('utf-8', 'ignore')
+ footer = footer
msg = msg + (footer or '')
if txt:
email.set_text(txt)
else:
try:
- msg_unicode = msg
- if isinstance(msg, str):
- msg_unicode = unicode(msg, 'utf-8', 'ignore')
- email.set_text(html2text(msg_unicode))
+ email.set_text(html2text(msg))
except HTMLParser.HTMLParseError:
pass
email.set_html(msg)
@@ -119,10 +115,10 @@ def get_contact_list():
"""
cond = ['`%s` like "%s%%"' % (f,
- webnotes.form.getvalue('txt')) for f in webnotes.form.getvalue('where').split(',')]
+ webnotes.form_dict.get('txt')) for f in webnotes.form_dict.get('where').split(',')]
cl = webnotes.conn.sql("select `%s` from `tab%s` where %s" % (
- webnotes.form.getvalue('select')
- ,webnotes.form.getvalue('from')
+ webnotes.form_dict.get('select')
+ ,webnotes.form_dict.get('from')
,' OR '.join(cond)
)
)
diff --git a/py/webnotes/utils/email_lib/form_email.py b/py/webnotes/utils/email_lib/form_email.py
index 35d749552b..7eef07461e 100644
--- a/py/webnotes/utils/email_lib/form_email.py
+++ b/py/webnotes/utils/email_lib/form_email.py
@@ -24,8 +24,6 @@ from __future__ import unicode_literals
import webnotes
from webnotes.utils import cint
-form = webnotes.form
-
from webnotes.utils.email_lib import get_footer
from webnotes.utils.email_lib.send import EMail
@@ -109,7 +107,7 @@ class FormEmail:
"""
al = []
try:
- al = webnotes.conn.sql('select file_list from `tab%s` where name="%s"' % (form.getvalue('dt'), form.getvalue('dn')))
+ al = webnotes.conn.sql('select file_list from `tab%s` where name="%s"' % (webnotes.form_dict.get('dt'), webnotes.form_dict.get('dn')))
if al:
al = (al[0][0] or '').split('\n')
except Exception, e:
@@ -145,12 +143,11 @@ class FormEmail:
# footer
footer = get_footer()
if footer:
- footer = footer.encode('utf-8')
html_message += footer
text_message += footer
# message as text
- self.email.set_text(html2text(unicode(text_message, 'utf-8')))
+ self.email.set_text(html2text(text_message))
self.email.set_html(html_message)
def make_communication(self):
diff --git a/py/webnotes/utils/email_lib/receive.py b/py/webnotes/utils/email_lib/receive.py
index acd26a6fcc..b9cdebbcda 100644
--- a/py/webnotes/utils/email_lib/receive.py
+++ b/py/webnotes/utils/email_lib/receive.py
@@ -63,7 +63,7 @@ class IncomingMail:
get utf-8 encoded part content
"""
try:
- return unicode(part.get_payload(decode=True),str(charset),"ignore").encode('utf8','replace')
+ return unicode(part.get_payload(decode=True),str(charset),"ignore")
except LookupError, e:
return part.get_payload()
diff --git a/py/webnotes/utils/email_lib/send.py b/py/webnotes/utils/email_lib/send.py
index 35fc51ccdb..b7812b22a2 100644
--- a/py/webnotes/utils/email_lib/send.py
+++ b/py/webnotes/utils/email_lib/send.py
@@ -62,9 +62,8 @@ class EMail:
Attach message in the text portion of multipart/alternative
"""
from email.mime.text import MIMEText
- if isinstance(message, unicode):
- message = message.encode('utf-8')
- part = MIMEText(message, 'plain', 'utf-8')
+ from webnotes.utils import get_encoded_string
+ part = MIMEText(get_encoded_string(message), 'plain', 'utf-8')
self.msg_multipart.attach(part)
def set_html(self, message):
@@ -72,9 +71,8 @@ class EMail:
Attach message in the html portion of multipart/alternative
"""
from email.mime.text import MIMEText
- if isinstance(message, unicode):
- message = message.encode('utf-8')
- part = MIMEText(message, 'html', 'utf-8')
+ from webnotes.utils import get_encoded_string
+ part = MIMEText(get_encoded_string(message), 'html', 'utf-8')
self.msg_multipart.attach(part)
def set_message(self, message, mime_type='text/html', as_attachment=0, filename='attachment.html'):
@@ -110,6 +108,8 @@ class EMail:
from email.mime.text import MIMEText
import mimetypes
+
+ from webnotes.utils import get_encoded_string
if not content_type:
content_type, encoding = mimetypes.guess_type(fname)
@@ -122,7 +122,7 @@ class EMail:
maintype, subtype = content_type.split('/', 1)
if maintype == 'text':
# Note: we should handle calculating the charset
- part = MIMEText(fcontent, _subtype=subtype)
+ part = MIMEText(fcontent, _subtype=subtype, _charset='utf-8')
elif maintype == 'image':
part = MIMEImage(fcontent, _subtype=subtype)
elif maintype == 'audio':
@@ -136,7 +136,8 @@ class EMail:
# Set the filename parameter
if fname:
- part.add_header('Content-Disposition', 'attachment', filename=fname)
+ part.add_header(b'Content-Disposition',
+ get_encoded_string("attachment; filename=%s" % fname))
self.msg_root.attach(part)
@@ -174,14 +175,14 @@ class EMail:
else:
import webnotes.model.doc
- from webnotes.utils import cint
+ from webnotes.utils import cint, get_encoded_string
# get defaults from control panel
es = webnotes.model.doc.Document('Email Settings','Email Settings')
- self.server = es.outgoing_mail_server.encode('utf-8') or getattr(conf,'mail_server','')
- self.login = es.mail_login.encode('utf-8') or getattr(conf,'mail_login','')
+ self.server = get_encoded_string(es.outgoing_mail_server or getattr(conf,'mail_server',''))
+ self.login = get_encoded_string(es.mail_login or getattr(conf,'mail_login',''))
self.port = cint(es.mail_port) or getattr(conf,'mail_port',None)
- self.password = es.mail_password.encode('utf-8') or getattr(conf,'mail_password','')
+ self.password = get_encoded_string(es.mail_password or getattr(conf,'mail_password',''))
self.use_ssl = cint(es.use_ssl) or cint(getattr(conf, 'use_ssl', ''))
def make_msg(self):
diff --git a/py/webnotes/utils/file_manager.py b/py/webnotes/utils/file_manager.py
index ec2de2c3fd..96a90c3c02 100644
--- a/py/webnotes/utils/file_manager.py
+++ b/py/webnotes/utils/file_manager.py
@@ -24,12 +24,10 @@ from __future__ import unicode_literals
import webnotes
def upload():
- form = webnotes.form
-
# get record details
- dt = form.getvalue('doctype')
- dn = form.getvalue('docname')
- at_id = form.getvalue('at_id')
+ dt = webnotes.form_dict.get('doctype')
+ dn = webnotes.form_dict.get('docname')
+ at_id = webnotes.form_dict.get('at_id')
webnotes.response['type'] = 'iframe'
if not webnotes.form['filedata'].filename:
diff --git a/py/webnotes/widgets/doclistview.py b/py/webnotes/widgets/doclistview.py
index 4ce774ac28..384b1eb33f 100644
--- a/py/webnotes/widgets/doclistview.py
+++ b/py/webnotes/widgets/doclistview.py
@@ -238,10 +238,10 @@ def export_query():
f = StringIO()
writer = csv.writer(f)
+ from webnotes.utils import get_encoded_string
for r in data:
for i in xrange(len(r)):
- if type(r[i]) is unicode:
- r[i] = r[i].encode('utf-8')
+ r[i] = get_encoded_string(r[i])
writer.writerow(r)
f.seek(0)
diff --git a/py/webnotes/widgets/event.py b/py/webnotes/widgets/event.py
index c7f15910e3..0337d152ee 100644
--- a/py/webnotes/widgets/event.py
+++ b/py/webnotes/widgets/event.py
@@ -61,11 +61,9 @@ def get_cal_events(m_st, m_end):
@webnotes.whitelist()
def load_month_events():
from webnotes.utils import cint
-
- form = webnotes.form
- mm = form.getvalue('month')
- yy = form.getvalue('year')
+ mm = webnotes.form_dict.get('month')
+ yy = webnotes.form_dict.get('year')
m_st = str(yy) + '-%.2i' % cint(mm) + '-01'
m_end = str(yy) + '-%.2i' % cint(mm) + '-31'
diff --git a/py/webnotes/widgets/form/load.py b/py/webnotes/widgets/form/load.py
index c24a6d76d0..acb7074145 100644
--- a/py/webnotes/widgets/form/load.py
+++ b/py/webnotes/widgets/form/load.py
@@ -63,10 +63,10 @@ def getdoctype():
import webnotes.model.doctype
import webnotes.model.meta
- form, doclist = webnotes.form, []
+ doclist = []
- dt = form.getvalue('doctype')
- with_parent = form.getvalue('with_parent')
+ dt = webnotes.form_dict.get('doctype')
+ with_parent = webnotes.form_dict.get('with_parent')
# with parent (called from report builder)
if with_parent:
diff --git a/py/webnotes/widgets/form/print_format.py b/py/webnotes/widgets/form/print_format.py
index f0c00f8b54..f2f0262684 100644
--- a/py/webnotes/widgets/form/print_format.py
+++ b/py/webnotes/widgets/form/print_format.py
@@ -28,7 +28,7 @@ def get():
"""load print format by `name`"""
import re
- html = get_html(webnotes.form.getvalue('name'))
+ html = get_html(webnotes.form_dict.get('name'))
p = re.compile('\$import\( (?P [^)]*) \)', re.VERBOSE)
out_html = ''
diff --git a/py/webnotes/widgets/form/run_method.py b/py/webnotes/widgets/form/run_method.py
index f27998e641..66498ee9d0 100644
--- a/py/webnotes/widgets/form/run_method.py
+++ b/py/webnotes/widgets/form/run_method.py
@@ -32,13 +32,11 @@ def runserverobj():
from webnotes.model.doclist import DocList
from webnotes.utils import cint
- form = webnotes.form
-
doclist = None
- method = form.getvalue('method')
- arg = form.getvalue('arg')
- dt = form.getvalue('doctype')
- dn = form.getvalue('docname')
+ method = webnotes.form_dict.get('method')
+ arg = webnotes.form_dict.get('arg')
+ dt = webnotes.form_dict.get('doctype')
+ dn = webnotes.form_dict.get('docname')
if dt: # not called from a doctype (from a page)
if not dn: dn = dt # single
@@ -46,7 +44,7 @@ def runserverobj():
else:
doclist = DocList()
- doclist.from_compressed(form.getvalue('docs'), dn)
+ doclist.from_compressed(webnotes.form_dict.get('docs'), dn)
so = doclist.make_obj()
doclist.check_if_latest()
@@ -56,7 +54,7 @@ def runserverobj():
r = webnotes.model.code.run_server_obj(so, method, arg)
if r:
#build output as csv
- if cint(webnotes.form.getvalue('as_csv')):
+ if cint(webnotes.form_dict.get('as_csv')):
make_csv_output(r, so.doc.doctype)
else:
webnotes.response['message'] = r
diff --git a/py/webnotes/widgets/form/utils.py b/py/webnotes/widgets/form/utils.py
index e9abffa76d..09ccabdf69 100644
--- a/py/webnotes/widgets/form/utils.py
+++ b/py/webnotes/widgets/form/utils.py
@@ -28,23 +28,23 @@ def remove_attach():
"""remove attachment"""
import webnotes.utils.file_manager
- fid = webnotes.form.getvalue('fid')
+ fid = webnotes.form_dict.get('fid')
# remove from dt dn
- return str(webnotes.utils.file_manager.remove_file(webnotes.form.getvalue('dt'), webnotes.form.getvalue('dn'), fid))
+ return str(webnotes.utils.file_manager.remove_file(webnotes.form_dict.get('dt'), webnotes.form_dict.get('dn'), fid))
@webnotes.whitelist()
def get_fields():
"""get fields"""
r = {}
args = {
- 'select':webnotes.form.getvalue('select')
- ,'from':webnotes.form.getvalue('from')
- ,'where':webnotes.form.getvalue('where')
+ 'select':webnotes.form_dict.get('select')
+ ,'from':webnotes.form_dict.get('from')
+ ,'where':webnotes.form_dict.get('where')
}
ret = webnotes.conn.sql("select %(select)s from `%(from)s` where %(where)s limit 1" % args)
if ret:
- fl, i = webnotes.form.getvalue('fields').split(','), 0
+ fl, i = webnotes.form_dict.get('fields').split(','), 0
for f in fl:
r[f], i = ret[0][i], i+1
webnotes.response['message']=r
@@ -55,7 +55,7 @@ def validate_link():
import webnotes
import webnotes.utils
- value, options, fetch = webnotes.form.getvalue('value'), webnotes.form.getvalue('options'), webnotes.form.getvalue('fetch')
+ value, options, fetch = webnotes.form_dict.get('value'), webnotes.form_dict.get('options'), webnotes.form_dict.get('fetch')
# no options, don't validate
if not options or options=='null' or options=='undefined':
diff --git a/py/webnotes/widgets/page.py b/py/webnotes/widgets/page.py
index 14b0d8cad1..700ebc1c66 100644
--- a/py/webnotes/widgets/page.py
+++ b/py/webnotes/widgets/page.py
@@ -96,7 +96,7 @@ def getpage():
"""
Load the page from `webnotes.form` and send it via `webnotes.response`
"""
- doclist = get(webnotes.form.getvalue('name'))
+ doclist = get(webnotes.form_dict.get('name'))
# send
webnotes.response['docs'] = doclist
diff --git a/py/webnotes/widgets/query_builder.py b/py/webnotes/widgets/query_builder.py
index df95bd707d..2011385de3 100644
--- a/py/webnotes/widgets/query_builder.py
+++ b/py/webnotes/widgets/query_builder.py
@@ -23,7 +23,6 @@
from __future__ import unicode_literals
import webnotes
-form = webnotes.form
session = webnotes.session
sql = webnotes.conn.sql
out = webnotes.response
@@ -231,16 +230,16 @@ def build_description_standard(meta, tl):
def runquery(q='', ret=0, from_export=0):
import webnotes.utils
- formatted = cint(form.getvalue('formatted'))
+ formatted = cint(webnotes.form_dict.get('formatted'))
# CASE A: Simple Query
# --------------------
- if form.getvalue('simple_query') or form.getvalue('is_simple'):
- if not q: q = form.getvalue('simple_query') or form.getvalue('query')
+ if webnotes.form_dict.get('simple_query') or webnotes.form_dict.get('is_simple'):
+ if not q: q = webnotes.form_dict.get('simple_query') or webnotes.form_dict.get('query')
if q.split()[0].lower() != 'select':
raise Exception, 'Query must be a SELECT'
- as_dict = cint(form.getvalue('as_dict'))
+ as_dict = cint(webnotes.form_dict.get('as_dict'))
res = sql(q, as_dict = as_dict, as_list = not as_dict, formatted=formatted)
# build colnames etc from metadata
@@ -249,7 +248,7 @@ def runquery(q='', ret=0, from_export=0):
# CASE B: Standard Query
# -----------------------
else:
- if not q: q = form.getvalue('query')
+ if not q: q = webnotes.form_dict.get('query')
tl = get_sql_tables(q)
meta = get_sql_meta(tl)
@@ -257,7 +256,7 @@ def runquery(q='', ret=0, from_export=0):
q = add_match_conditions(q, tl, webnotes.user.roles, webnotes.user.get_defaults())
webnotes
# replace special variables
- q = q.replace('__user', session['user'].encode('utf-8'))
+ q = q.replace('__user', session['user'])
q = q.replace('__today', webnotes.utils.nowdate())
res = sql(q, as_list=1, formatted=formatted)
@@ -267,8 +266,8 @@ def runquery(q='', ret=0, from_export=0):
# run server script
# -----------------
style, header_html, footer_html, page_template = '', '', '', ''
- if form.has_key('sc_id') and form.getvalue('sc_id'):
- sc_id = form.getvalue('sc_id')
+ if form.has_key('sc_id') and webnotes.form_dict.get('sc_id'):
+ sc_id = webnotes.form_dict.get('sc_id')
from webnotes.model.code import get_code
sc_details = webnotes.conn.sql("select module, standard, server_script from `tabSearch Criteria` where name=%s", sc_id)[0]
if sc_details[1]!='No':
@@ -277,7 +276,7 @@ def runquery(q='', ret=0, from_export=0):
code = sc_details[2]
if code:
- filter_values = form.has_key('filter_values') and eval(form.getvalue('filter_values','')) or {}
+ filter_values = form.has_key('filter_values') and eval(webnotes.form_dict.get('filter_values','')) or {}
res, style, header_html, footer_html, page_template = exec_report(code, res, colnames, colwidths, coltypes, coloptions, filter_values, q, from_export)
out['colnames'] = colnames
@@ -298,7 +297,7 @@ def runquery(q='', ret=0, from_export=0):
out['values'] = res
# return num of entries
- qm = form.has_key('query_max') and form.getvalue('query_max') or ''
+ qm = form.has_key('query_max') and webnotes.form_dict.get('query_max') or ''
if qm and qm.strip():
if qm.split()[0].lower() != 'select':
raise Exception, 'Query (Max) must be a SELECT'
@@ -315,9 +314,9 @@ def runquery_csv():
# run query
res = runquery(from_export = 1)
- q = form.getvalue('query')
+ q = webnotes.form_dict.get('query')
- rep_name = form.getvalue('report_name')
+ rep_name = webnotes.form_dict.get('report_name')
if not form.has_key('simple_query'):
# Report Name
@@ -336,10 +335,10 @@ def runquery_csv():
f = StringIO()
writer = csv.writer(f)
+ from webnotes.utils import get_encoded_string
for r in rows:
for i in xrange(len(r)):
- if type(r[i]) is unicode:
- r[i] = r[i].encode('utf-8')
+ r[i] = get_encoded_string(r[i])
writer.writerow(r)
f.seek(0)
diff --git a/py/webnotes/widgets/search.py b/py/webnotes/widgets/search.py
index 7780c04a78..82632f4ca2 100644
--- a/py/webnotes/widgets/search.py
+++ b/py/webnotes/widgets/search.py
@@ -30,13 +30,13 @@ def getsearchfields():
sf = webnotes.conn.sql("""\
SELECT value FROM `tabProperty Setter`
WHERE doc_type=%s AND property='search_fields'""", \
- (webnotes.form.getvalue("doctype")))
+ (webnotes.form_dict.get("doctype")))
if not (sf and len(sf)>0 and sf[0][0]):
- sf = webnotes.conn.sql("select search_fields from tabDocType where name=%s", webnotes.form.getvalue("doctype"))
+ sf = webnotes.conn.sql("select search_fields from tabDocType where name=%s", webnotes.form_dict.get("doctype"))
sf = sf and sf[0][0] or ''
sf = [s.strip() for s in sf.split(',')]
if sf and sf[0]:
- res = webnotes.conn.sql("select fieldname, label, fieldtype, options from tabDocField where parent='%s' and fieldname in (%s)" % (webnotes.form.getvalue("doctype","_NA"), '"'+'","'.join(sf)+'"'))
+ res = webnotes.conn.sql("select fieldname, label, fieldtype, options from tabDocField where parent='%s' and fieldname in (%s)" % (webnotes.form_dict.get("doctype","_NA"), '"'+'","'.join(sf)+'"'))
else:
res = []
@@ -101,9 +101,9 @@ def scrub_custom_query(query, key, txt):
def search_link():
import webnotes.widgets.query_builder
- txt = webnotes.form.getvalue('txt')
- dt = webnotes.form.getvalue('dt')
- query = webnotes.form.getvalue('query')
+ txt = webnotes.form_dict.get('txt')
+ dt = webnotes.form_dict.get('dt')
+ query = webnotes.form_dict.get('query')
# txt - decode it to utf-8. why to do this?
# "%(something_unicode)s %(something ascii encoded with utf-8)s"
@@ -125,10 +125,10 @@ def search_link():
def search_widget():
import webnotes.widgets.query_builder
- dt = webnotes.form.getvalue('doctype')
- txt = webnotes.form.getvalue('txt') or ''
- key = webnotes.form.getvalue('searchfield') or 'name' # key field
- user_query = webnotes.form.getvalue('query') or ''
+ dt = webnotes.form_dict.get('doctype')
+ txt = webnotes.form_dict.get('txt') or ''
+ key = webnotes.form_dict.get('searchfield') or 'name' # key field
+ user_query = webnotes.form_dict.get('query') or ''
# txt - decode it to utf-8. why to do this?
# "%(something_unicode)s %(something ascii encoded with utf-8)s"
@@ -139,6 +139,6 @@ def search_widget():
if user_query:
query = scrub_custom_query(user_query, key, txt)
else:
- query = make_query(', '.join(get_std_fields_list(dt, key)), dt, key, txt, webnotes.form.getvalue('start') or 0, webnotes.form.getvalue('page_len') or 50)
+ query = make_query(', '.join(get_std_fields_list(dt, key)), dt, key, txt, webnotes.form_dict.get('start') or 0, webnotes.form_dict.get('page_len') or 50)
webnotes.widgets.query_builder.runquery(query)