Change form language with WtForm and Flask? - flask

Sorry for being a newbie but I am having troubles changing the language for a form. I am trying out Flask with wtform but I cant change the text for name, email, etc to my native language.
class ContactForm(Form):
name = StringField("Name", [validators.Required("Skriv in ditt namn")])
email = StringField("Email", [validators.Required("Skriv inepostadress"), validators.Email("Är det verkligen din epostadress?")])
subject = StringField("Subject")
message = TextAreaField("Message", [validators.Required("Skriv in ett meddelande")])
recaptcha = RecaptchaField()
submit = SubmitField("Send")
How do I change the language so that I can use swedish chars "ÅÄÖ"? For example I want to change the value StringField("Name") to StringField("Nåme")

To use special characters in your source code it is always a good idea to have:
# -*- coding: utf8 -*-
At the top of the file. This will allow Python to read the file correctly.
In your case you need to append a u to the start of your string. This marks the string as Unicode u"Är det verkligen din epostadress?"
This should only be needed in Python 2. In Python 3 strings are unicode by default.

Related

scraping chinese characters python

I learnt how to scrap website from https://automatetheboringstuff.com. I wanted to scrap http://www.piaotian.net/html/3/3028/1473227.html in which the contents is in chinese and write its contents into a .txt file. However, the .txt file contains random symbols which I assume is a encoding/decoding problem.
I've read this thread "how to decode and encode web page with python?" and figured the encoding method for my site is "gb2312" and "windows-1252". I tried decoding in those two encoding methods but failed.
Can someone kindly explain to me the problem with my code? I'm very new to programming so please let me know my misconceptions as well!
Also, when I remove the "html.parser" from the code, the .txt file turns out to be empty instead of having at least symbols. Why is this the case?
import bs4, requests, sys
reload(sys)
sys.setdefaultencoding("utf-8")
novel = requests.get("http://www.piaotian.net/html/3/3028/1473227.html")
novel.raise_for_status()
novelSoup = bs4.BeautifulSoup(novel.text, "html.parser")
content = novelSoup.select("br")
novelFile = open("novel.txt", "w")
for i in range(len(content)):
novelFile.write(str(content[i].getText()))
novel = requests.get("http://www.piaotian.net/html/3/3028/1473227.html")
novel.raise_for_status()
novel.encoding = "GBK"
novelSoup = bs4.BeautifulSoup(novel.text, "html.parser")
out:
<br>
一元宗,坐落在青峰山上,绵延极长,现在是盛夏时节,天空之中,太阳慢慢落了下去,夕阳将影子拉的很长。<br/>
<br/>
一片不是很大的小湖泊边上,一个约莫着十七八岁的青衣少年坐在湖边,抓起湖边的一块石头扔出,顿时在湖边打出几朵浪花。<br/>
<br/>
叶希文有些茫然,他没想到,他居然穿越了,原本叶希文只是二十一世纪的地球上一个普通的大学生罢了,一个月了,他才后知后觉的反应过来,这不是有人和他进行恶作剧,而是,他真的穿越了。<br/>
Requests will automatically decode content from the server. Most
unicode charsets are seamlessly decoded.
When you make a request, Requests makes educated guesses about the
encoding of the response based on the HTTP headers. The text encoding
guessed by Requests is used when you access r.text. You can find out
what encoding Requests is using, and change it, using the r.encoding
property:
>>> r.encoding
'utf-8'
>>> r.encoding = 'ISO-8859-1'
If you change the encoding, Requests will use the new value of
r.encoding whenever you call r.text.

Python - Text does not appear in code-triggered email sent if string is result of a formula

I am attempting to write a program that sends an email from Gmail, with a body of text that includes real time stock quotes. I am using a module to get stock quotes in string format (this works), and I wrote a function to send an email from gmail. The message_send function is only working if I give it a simple string. It is not working if I pass it the aapl_string variable. See code below:
from yahoo_finance import *
import smtplib
def message_send(messagebody):
fromaddr = 'REDACTED'
toaddrs = 'REDACTED'
msg = messagebody
# Credentials (if needed)
username = 'REDACTED'
password = 'REDACTED'
# The actual mail send
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
aapl = Share('AAPL')
aapl.refresh()
price_aapl = aapl.get_price()
aapl_string = "The current price of AAPL is: " + price_aapl
print(aapl_string)
message_send(aapl_string)
Any ideas why the email sends, but contains blank text when using aapl_string as the argument for the message_send function?
Thanks!
You could do
message_send("The current value is %s" %price_aapl)
and that should make it work :)
I'm assuming price_aapl is an integer, and if that's the case then that is your whole problem. This is due to the inability of being able to add integers to strings so what you could do is use a format string.
ex:
aapl_string = "The current price of AAPL is: %d" % price_aapl
the %d is a placeholder for the integer price_aapl.
You can look here -> http://www.diveintopython.net/native_data_types/formatting_strings.html
for more information on formatting strings in python.

Django testing view input with different character sets

I'm having trouble trying to generate a test for my views. I've a view, that consumes in a given input from form, some characters. That characters are commited to DB, without problems.
All I was trying was to generate a test to ensure that different characters, from different languages, were accepted.
I tested this one:
Český jazyk neboli čeština
This input is correctly got from HTML form, and stored in DB. When I try to set this one from test, something weird happens, and view throws an error, saying that
Warning: Incorrect string value: '\xC4\x8Cesk\xC3...' for column 'title' at row 1
My code is as simple as follows:
str1 = "Český jazyk neboli čeština"
self.client.post(url, {"title": str1})
And tryied all combinations:
str1 = u"..."
str1 = str1.encode('utf-8')
str1 = str1.decode('utf-8')
Without any success.
Can anyone tell me what I'm missing?
Thank you in advance
First of all: Make sure you have included this at the beginning of your script:
#-*- coding: utf-8 -*-
That is to tell the interpreter that this file's encoding is utf-8 (make sure it is from your text editor)
Second: instead of
str1 = "Český jazyk neboli čeština"
declare the str1 as unicode like this:
str1 = u"Český jazyk neboli čeština"
Now, I'll suggest you that if you want to include non ascii chars, declare them with their proper unicode code instead of the character to avoid weird encoding issues.
str1 = u'\u010cesk\xfd jazyk neboli \u010de\u0161tina'
This is a useful page to check characters unicode code
Hope this helps!

How to read the contents of active directory using python-ldap?

My script is like this:
import ldap, sys
server = 'ldap://my_server'
l = ldap.initialize(server)
dn="myname#mydomain"
pw = "password"
l.simple_bind_s(dn,pw)
ldap.set_option(ldap.OPT_REFERRALS,0)
print "valid"
I am using Python 2.7 on windows.
Is there any method to read or get the contents of active directory?
You can do quite a lot also using win32com.client (which I had trouble finding documentation for). For example I've needed to resolve user email knowing his ADS_NAME_TYPE_NT4 formatted name (doman\jonjoe).
First of all you need to convert it to ADS_NAME_TYPE_1779 format (CN=Jeff Smith,CN=users,DC=Fabrikam,DC=com):
name_resolver = win32com.client.Dispatch(dispatch='NameTranslate')
name_resolver.Set(3, 'domain\\jonjoe')
ldap_query = 'LDAP://{}'.format(name_resolver.Get(1))
Once you have that you can simply call GetObject():
ldap = win32com.client.GetObject(ldap_query)
print(ldap.Get('mail'))
Tested with Python 3.2.5
You should realy need to read the documentation of python-ldap http://www.python-ldap.org/docs.shtml
You have a connection in your variable l, then you can do this.
l.con_search_s('dc=your,dc=base,dc=dit', ldap.SCOPE_SUBTREE, 'uid=*', ['uid', 'uidnumber'])
The above code, goint to search in to all the uid's entrys, for if entry, is going to get the uid and the uidnumbre attributes.

How can i add bengali font in a django web application

I want to create a quiz web application using django where the quiz question will be in Bengali. How can i generate the bengali font in my desired site.
Please if anyone tell me .. i will be grateful to him
Django is not involved in font rendering on the browser. Embedding a particular font via CSS is still problematical until today. You may find answers at How to embed fonts in HTML?.
In Django, you specify only the character codes. You may have to use unicode escape sequences in strings, unless you can enter Bengali characters directly. Bengali characters reside in the unicode range U+0981 to U+09FA. I assume that your target audience will have glyphs installed for those characters, so there may be no need to provide an embedded font at all.
You can use the following script to display a list of the defined Bengali unicode characters.
import sys
import unicodedata as ucd
try:
chr = unichr
except NameError:
# Python 3
unicode = str
def filter_bengali():
for i in range(256, sys.maxunicode + 1):
try:
name = ucd.name(chr(i))
if 'BENGALI' in name:
print(unicode('U+{0:04X} {1:<60} {2}').format(i, name, chr(i)))
except ValueError:
pass
if __name__ == '__main__':
filter_bengali()