I'm trying to make a form that handles the checking of a domain: the form should fail based on a variable that was set earlier in another form.
Basically, when a user wants to create a new domain, this form should fail if the entered domain exists.
When a user wants to move a domain, this form should fail if the entered domain doesn't exist.
I've tried making it dynamic overload the initbut couldn't see a way to get my passed variabele to the clean function.
I've read that this dynamic validation can be accomplished using a factory method, but maybe someone can help me on my way with this?
Here's a simplified version of the form so far:
#OrderFormStep1 presents the user with a choice: create or move domain
class OrderFormStep2(forms.Form):
domain = forms.CharField()
extension = forms.CharField()
def clean(self):
cleaned_data = self.cleaned_data
domain = cleaned_data.get("domain")
extension = cleaned_data.get("extension")
if domain and extension:
code = whoislookup(domain+extension);
#Raise error based on result from OrderFormStep1
#raise forms.ValidationError('error, domain already exists')
#raise forms.ValidationError('error, domain does not exist')
return cleaned_data
I have a simple rules/conditions table in my database which is used to generate alerts for one of our systems. I want to create a rules engine or a domain specific language.
A simple rule stored in this table would be..(omitting the relationships here)
if temp > 40 send email
Please note there would be many more such rules. A script runs once daily to evaluate these rules and perform the necessary actions. At the beginning, there was only one rule, so we had the script in place to only support that rule. However we now need to make it more scalable to support different conditions/rules. I have looked into rules engines , but I hope to achieve this in some simple pythonic way. At the moment, I have only come up with eval/exec and I know that is not the most recommended approach. So, what would be the best way to accomplish this??
( The rules are stored as data in database so each object like "temperature", condition like "/=..etc" , value like "40,50..etc" and action like "email, sms, etc.." are stored in the database, i retrieve this to form the condition...if temp 50 send email, that was my idea to then use exec or eval on them to make it live code..but not sure if this is the right approach )
I am trying to return the duration of the video but am having trouble.
#YOUTUBE FEED
#download the file:
file = urllib2.urlopen('http://gdata.youtube.com/feeds/api/videos/2s0vk2wEMtA')
#convert to string:
data = file.read()
#close file because we dont need it anymore:
file.close()
#entire feed
root = etree.fromstring(data)
for entry in root:
for item in entry:
print item
When I print item, I see as the last element:
Element '{http://gdata.youtube.com/schemas/2007}duration' at 0x10c4fb7d0
But I don't know how to get the value from this. Any advice?
I am building music app, where user can do several tasks including but not limited to listening song, like song, recommend song to a friend and extra.
currently I have this model:
class Activity(models.Model):
activity = models.TextField()
user = models.ForeignKey(User)
date = models.DateTimeField(auto_now=True)
so far I thought about two solutions.
1. saving a string to database. e.g "you listened song xyz"
2. create a dictionary about the activity and save to the database using pickle or json. e.g.
dict_ = {"activity_type":"listening", "song":song_obj}
I am leaning to the second implementation, but not quite sure.
so what do you think about those two methods? do you know better way to achieve the goal?
I have a very simple application running on appengine that requests a web page every five minutes and parses for a specific piece of data.
Everything works fine except that the response I get back from the external request (using urllib2) doesn't reflect the latest changes to the page. Sometimes it takes a few minutes to get the latest, sometimes over an hour.
Is there a transparent layer of caching that appengine puts in place? Or is there something else I am missing here? I've looked at the caching headers of the requested page and there is no Expires or LastModified's sent.
Update:
Sometimes, it will get the new version of the page for a number of requests and then randomly later get an old out of date version.
This code in PHP sends a HTTP POST to a Django app using CURL lib.
I need that this code sends POST but redirect to the page in the same submit. Like a simple form does.
The PHP Code:
$c = curl_init();
curl_setopt($c, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($c, CURLOPT_URL, "http://www.xxx.com");
curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_POSTFIELDS, 'Var='.$var);
curl_exec($c);
curl_close ($c);
In this case, the PHP is sending the HTTP POST, but is not redirecting to the page. He is printing the result. My URL still .php and not a django/url/
I need be redirected to the django URL with the Post like a simple form in HTML does.
Any Idea?
Thanks.
Hello!
I want to enable debug (DEBUG = True) For my Django project only if it runs on localhost. How can I get user IP address inside settings.py? I would like something like this to work:
#Debugging only on localhost
if user_ip = '127.0.0.1':
DEBUG = True
else:
DEBUG = False
How do I put user IP address in user_ip variable inside settings.py file?
this is my code :
import os
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
#from login import htmlPrefix,get_current_user
class MyModel(db.Model):
blob = db.BlobProperty()
class BaseRequestHandler(webapp.RequestHandler):
def render_template(self, filename, template_args=None):
if not template_args:
template_args = {}
path = os.path.join(os.path.dirname(__file__), 'templates', filename)
self.response.out.write(template.render(path, template_args))
class upload(BaseRequestHandler):
def get(self):
self.render_template('index.html',)
def post(self):
file=self.request.get('file')
obj = MyModel()
obj.blob = db.Blob(file.encode('utf8'))
obj.put()
self.response.out.write('upload ok')
class download(BaseRequestHandler):
def get(self):
#id=self.request.get('id')
o = MyModel.all().get()
#self.response.out.write(''.join('%s: %s <br/>' % (a, getattr(o, a)) for a in dir(o)))
self.response.out.write(o)
application = webapp.WSGIApplication(
[
('/?', upload),
('/download',download),
],
debug=True
)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
my index.html is :
<form action="/" method="post">
<input type="file" name="file" />
<input type="submit" />
</form>
and it show :
<__main__.MyModel object at 0x02506830>
but ,i don't want to see this , i want to download it ,
how to change my code to run,
thanks
I'm wondering what the best approach to take here is. I've got a form that people use to register for a class and a lot of times the manager of a company will register multiple people for the class at the same time. Presently, they'd have to go through the registration process multiple times and resubmit the form once for every person they want to register.
What I want to do is give the user a form that has a single <input/> for one person to register with, along with all the other fields they'll need to fill out (Email, phone number, etc); if they want to add more people, they'll be able to press a button and a new <input/> will be generated. This part I know how to do, but I'm including it to best describe what I'm aiming to do.
The part I don't know how to approach is processing that data the form submits, I need some way of making a new row in the Registrant table for every <input/> that's added and include the same contact information (phone, email, etc) as the first row with that row. For the record, I'm using the Django framework for my back-end code.
What's the best approach here? Should it just POST the form x times for x people, or is there a less "brute force" way of handling this?
Just started looking into metaclasses and while they seem powerful, I can think of other ways to accomplish the same type of thing. I was wondering when metaclasses have been found to be the right answer and why.
info = {'phone_number': '123456', 'personal_detail': {'foo':foo, 'bar':bar}, 'is_active': 1, 'document_detail': {'baz':baz, 'saz':saz}, 'is_admin': 1, 'email': '[email protected]'}
return HttpResponse(simplejson.dumps({'success':'True', 'result':info}), mimetype='application/javascript')
if(data["success"] === "True") {
alert(data[**here I want to display personal_detail and document_details**]);
}
How can I do this?
im using the example from the pylons book
orm.mapper(Comment, comment_table)
orm.mapper(Tag, tag_table)
orm.mapper(Nav, nav_table, polymorphic_on=nav_table.c.type, polymorphic_identity='nav')
orm.mapper(Section, section_table, inherits=Nav, polymorphic_identity='section')
orm.mapper(Page, page_table, inherits=Nav, polymorphic_identity='page', properties={
'comments':orm.relation(Comment, backref='page', cascade='all'),
'tags':orm.relation(Tag, secondary=pagetag_table)
})
i am mostly copying from this, but is there a simple way have a default Page that gets referenced, but if users requests a change, create a new Page object? thanks
i want something similar to this
class DefaultPage(Page):
__init__(self):
self.a = a
self.b = b
self.c = c
orm.mapper(DefaultPage, None, inherits=Nav, yada yada )
Good Morning
i'm currently facing a problem in my Cherrypy application.
Im my own custom session module , anyway when performing session.add()
The exact same object gets updated Twice.
cherrypy.request.SessionManager.user_data = user
try:
db_session.add(cherrypy.request.SessionManager)
db_session.commit()
Will Return
2011-06-21 09:16:48,991 INFO sqlalchemy.engine.base.Engine.0x...04cL BEGIN (implicit)
2011-06-21 09:16:49,015 INFO sqlalchemy.engine.base.Engine.0x...04cL SELECT .....
FROM "Clients_Users"
WHERE "Clients_Users".username = %(username_1)s AND "Clients_Users".password = %(password_1)s
LIMIT 1 OFFSET 0
2011-06-21 09:16:49,015 INFO sqlalchemy.engine.base.Engine.0x...04cL {'password_1': '123', 'username_1': u'1'}
2011-06-21 09:16:49,047 INFO sqlalchemy.engine.base.Engine.0x...04cL UPDATE "SYS_Sessions" SET user_data=%(user_data)s WHERE "SYS_Sessions".id = %(SYS_Sessions_id)s
2011-06-21 09:16:49,067 INFO sqlalchemy.engine.base.Engine.0x...04cL {'SYS_Sessions_id': 92L, 'user_data': }
2011-06-21 09:16:49,071 INFO sqlalchemy.engine.base.Engine.0x...04cL COMMIT
2011-06-21 09:16:49,093 INFO sqlalchemy.engine.base.Engine.0x...04cL BEGIN (implicit)
2011-06-21 09:16:49,095 INFO sqlalchemy.engine.base.Engine.0x...04cL UPDATE "SYS_Sessions" SET user_data=%(user_data)s WHERE "SYS_Sessions".id = %(SYS_Sessions_id)s
2011-06-21 09:16:49,095 INFO sqlalchemy.engine.base.Engine.0x...04cL {'SYS_Sessions_id': 92L, 'user_data': }
2011-06-21 09:16:49,108 INFO sqlalchemy.engine.base.Engine.0x...04cL COMMIT
As Anyone seen this before ?
P.S This doesn't happen in the rest of the modules i have made.
If you are familiar with Django, you know that they have a Authentication system with User model. Of course, I have many other tables that have a Foreign Key to this User model.
If I want to delete this user, how do I architect a script (or through mysql itself) to delete every table that is related to this user?
My only worry is that I can do this manually...but if I add a table , but I forget to add that table to my DELETE operation...then I have a row that links to a deleted, non-existing User.
I have multiple greenlets sending on a common socket. Is it guaranteed that each package sent via socket.sendall is well separated or do I have to acquire a lock before each call to sendall.
So I want to prevent the following scenario:
g1 sends ABCD
g2 sends 1234
received data is mixed up, for example AB1234CD
expected is either ABCD1234 or 1234ABCD
Update
After a look at the sourcecode I think this scenario cannot happen. But I have to use a lock because g1 or g2 can crash on the sendall. Can someone confirm this?
formbuild's start_with_layout generates this code
<form action="link" method="post"><table>
how do i add id to it? i wanna add some js things that adds elements
I have two identically-sized numpy.array objects (both one-dimensional), one of which contains a list of starting index positions, and the other of which contains a list of ending index positions (alternatively you could say I have a list of starting positions and window lengths). In case it matters, the slices formed by the starting and ending positions are guaranteed to be non-overlapping. I am trying to figure out how to use these starting and ending positions to form an index for another array object, without having to use a loop.
For example:
import numpy as np
start = np.array([1,7,20])
end = np.array([3,10,25])
Want to reference
somearray[1,2,7,8,9,20,21,22,23,24])
This line:
used_emails = [row.email for row
in db.execute(select([halo4.c.email], halo4.c.email!=''))]
Returns:
['[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]']
I use this to find a match:
if recipient in used_emails:
If it finds a match I need to pull another field (halo4.c.code) from the database in the same row. Any suggestions on how to do this?
So, you build a great shiny cloudy 2.0 website on top of AppEngine, with thousands upon thousands of images saved into the datastore and gigs of data at the blobstore. How do you backup them?
In the tornado.web module there is a function called _time_independent_equals:
def _time_independent_equals(a, b):
if len(a) != len(b):
return False
result = 0
for x, y in zip(a, b):
result |= ord(x) ^ ord(y)
return result == 0
It is used to compare secure cookie signatures, and thus the name.
But regarding the implementation of this function, is it just a complex way to say a==b?
i want to get the values of the last 30 frames of the first wav file and first thirty frames of the second wave file in integer format and stored in a list or array.
i have written the code for joining but during this manupalation i am getting in byte format and tried to convert it to integer but couldn't.
as told before i want to get the frame detail of 1st 30 and last 30 in integer format,and by performing other operations join can be more successful
looking for your help in this,please...
thanking you,
import wave
m=['C:/begpython/S0001_0002.wav', 'C:/begpython/S0001_0001.wav']
i=1
a=m[i]
infiles = [a]
outfile = "C:/begpython/S0001_00367.wav"
data= []
data1=[]
for infile in infiles:
w = wave.open(infile, 'rb')
data1=[w.getnframes]
#print w.readframes(100)
data.append( [w.getparams(), w.readframes(w.getnframes())] )
#print w.readframes(1)
#data1 = [ord(character) for character in data1]
#print data1
#data1 = ''.join(chr(character) for character in data1)
w.close()
print data
output = wave.open(outfile, 'wb')
output.setparams(data[0][0])
output.writeframes(data[0][1])
output.writeframes(data[1][1])
output.writeframes(data[2][1])
output.close()