wildcard subdomains in a django project - python

has anyone ever used wildcard subdomains in their application? I need to come up with a way to 'localise' my application. When i say localise i mean anyone who goes to ny.foo.com/items/new/ will be sent to a view which looks through a database and search for new items in ny. Obviously we could replace NY with any state.
Any tips would be great
Thanks!

I would do it using a middleware, eg.:
class StateCodeMiddleware(object):
def process_request(self, request):
bits = request.META['HTTP_HOST'].split('.')
if len(bits) == 3 and len(bits[0]) == 2:
request.state_code = bits[0]
else:
request.state_code = None
# Or a redirect to the default state.
And then in any of your views, you can just check request.state_code and fetch new items only for that state.
Edit: For development, the best method is to setup a local DNS server. Eg. dnsmasq is very easy to configure:
address=/.dev/127.0.0.1 # in dnsmasq.conf
This makes *.dev point to localhost. You'll also have to configure your system to use the local DNS server (on UNIX systems you do this by placing nameserver 127.0.0.1 into /etc/resolve.conf).
Alternatively, you can list all the domain names in your /etc/hosts if it is a finite set:
127.0.0.1 ny.localhost, az.localhost # and so on

Related

pyvmomi retrieving vim.host.Summary.QuickStats

At this moment i am tryging to retrieve the quickstats of an ESXI host itself.
This is the way i connect :
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
context.verify_mode = ssl.CERT_NONE
si = SmartConnect(host=args.host,
user=args.user,
pwd=password,
port=int(args.port),
sslContext=context)
How do i retrieve the following stats with this library?
https://github.com/vmware/pyvmomi/blob/master/docs/vim/host/Summary/QuickStats.rst
First you need to locate your host, then access the properties like so:
content = si.RetrieveContent()
host = content.searchIndex.FindByDnsName(dnsName="DC0_C0_H0", vmSearch=False)
print host.summary.quickStats.uptime
The method Im using to locate the host does not have to be used.. its just one of MANY ways of finding a host.. This example assumes you only need to do this for 1 or 2 hosts... Assuming you have lots of hosts and dont want the call to be slow you would really want to build a property collector to fetch that data or else the call will take ages.. If you look at the community samples there is an example or 2 that use views and property collectors which will make your code fast and scaleable.

How to Limit Ratings (or anything else in Django) by IP?

I am using DjangoRatings for a web app which allows anonymous ratings from registered as well as nonregistered users. After I set the IPLimit integer in the DjangoRatings settings.py file, everything works fine; however, when I exceed the number of votes that I have allowed per IP, the entire web page gets reloaded with an “RaiseIPLimit()” error and the entire site goes down which necessitates reloading the previous page via back button. My question is, what can I add to my views.py file to tell django that when DjangoRatings passes the RaiseIPLimit() error, simply print something like “You can only vote once!” message to the user and leave the loaded web page as it is instead of crashing the entire site.
If there’s an easier way to do this general IP checking besides DjangoRatings, I am open to implementing other ways, but DjangoRatings just seems much easier than anything else since the only thing I need IP limits on is rating stuff. To be more clear, here is the exact error that DjangoRatings gives me:
IPLimitReached at /myapp/rating /page1
And this is straight from the DjangoRatings source code:
num_votes = Vote.objects.filter(
content_type=kwargs['content_type'],
object_id=kwargs['object_id'],
key=kwargs['key'],
ip_address=ip_address,
).count()
if num_votes >= getattr(settings, 'RATINGS_VOTES_PER_IP', RATINGS_VOTES_PER_IP):
raise IPLimitReached() ...
kwargs.update(defaults)
if use_cookies:
# record with specified cookie was not found ...
cookie = defaults['cookie'] # ... thus we need to replace old cookie (if presented) with new one
kwargs.pop('cookie__isnull', '') # ... and remove 'cookie__isnull' (if presented) from .create()'s **kwargs
rating, created = Vote.objects.create(**kwargs), True

Integration OpenERP with Asterisk

I'm trying to integrate OpenERP and Asterisk with asterisk_click2dial module. Calling from softphone to softphone works, but i cant call from OpenERP to softphone.
manager.conf:
[general]
enabled = yes
webenabled = yes
port = 5038
bindaddr = 0.0.0.0
[openerp]
secret = openerp
deny=0.0.0.0/0.0.0.0
permit=0.0.0.0/0.0.0.0
read = system,call,log,verbose,command,agent,user
write = system,call,log,verbose,command,agent,user
asterisk server config (img)
I'm sure, user settings are ok.
It doesn't works when AMI login is phone number, like in softphone config.
python debugg:
[2012-04-17 14:17:44,072][asterisk] INFO:asterisk_click2dial:Asterisk Click2Dial from 103 to 101
[2012-04-17 14:17:44,078][asterisk] WARNING:web-services:The method action_dial_phone of the object crm.lead can not return `None` !
asterisk server debugg:
== connect attempt from '192.168.1.106' unable to authenticate
While catching SIP packages by Wireshark i saw only reciver number (101#192.168.1.100). I didn't see openerp user number (103), but only Unknown#192.168.1.106. But i first time used Wireshark, so maybe it doesn't matter.
Question is: why OpenERP can't call to softphone, but softphone to softphone can?
Sorry for my english :)
You need to concentrate on the authentication side. If OpenERP (which I am not familiar with) can only send a phone number (or extension number) as a username, then you need to set that as your username in manager.conf. The username portion is what's between the [ and ] above (in this case it's [openerp]. If you do not have the flexibility to set an actual username on the client side of OpenERP, then you'll need to simply replace the [openerp] with [phone_no or ext_no].
Then it should authenticate fine. Wireshark isn't likely to be terribly helpful in this instance.

Programmatically detect system-proxy settings on Windows XP with Python

I develop a critical application used by a multi-national company. Users in offices all around the globe need to be able to install this application.
The application is actually a plugin to Excel and we have an automatic installer based on Setuptools' easy_install that ensures that all a project's dependancies are automatically installed or updated any time a user switches on their Excel. It all works very elegantly as users are seldom aware of all the installation which occurs entirely in the background.
Unfortunately we are expanding and opening new offices which all have different proxy settings. These settings seem to change from day to day so we cannot keep up with the outsourced security guys who change stuff without telling us. It sucks but we just have to work around it.
I want to programatically detect the system-wide proxy settings on the Windows workstations our users run:
Everybody in the organisazation runs Windows XP and Internet Explorer. I've verified that everybody can download our stuff from IE without problems regardless of where they are int the world.
So all I need to do is detect what proxy settings IE is using and make Setuptools use those settings. Theoretically all of this information should be in the Registry.. but is there a better way to find it that is guaranteed not to change with people upgrade IE? For example is there a Windows API call I can use to discover the proxy settings?
In summary:
We use Python 2.4.4 on Windows XP
We need to detect the Internet Explorer proxy settings (e.g. host, port and Proxy type)
I'm going to use this information to dynamically re-configure easy_install so that it can download the egg files via the proxy.
UPDATE0:
I forgot one important detail: Each site has an auto-config "pac" file.
There's a key in Windows\CurrentVersion\InternetSettings\AutoConfigURL which points to a HTTP document on a local server which contains what looks like a javascript file.
The pac script is basically a series of nested if-statements which compare URLs against a regexp and then eventually return the hostname of the chosen proxy-server. The script is a single javascript function called FindProxyForURL(url, host)
The challenge is therefore to find out for any given server which proxy to use. The only 100% guaranteed way to do this is to look up the pac file and call the Javascript function from Python.
Any suggestions? Is there a more elegant way to do this?
Here's a sample that should create a bullet green (proxy enable) or red (proxy disable) in your systray
It shows how to read and write in windows registry
it uses gtk
#!/usr/bin/env python
import gobject
import gtk
from _winreg import *
class ProxyNotifier:
def __init__(self):
self.trayIcon = gtk.StatusIcon()
self.updateIcon()
#set callback on right click to on_right_click
self.trayIcon.connect('popup-menu', self.on_right_click)
gobject.timeout_add(1000, self.checkStatus)
def isProxyEnabled(self):
aReg = ConnectRegistry(None,HKEY_CURRENT_USER)
aKey = OpenKey(aReg, r"Software\Microsoft\Windows\CurrentVersion\Internet Settings")
subCount, valueCount, lastModified = QueryInfoKey(aKey)
for i in range(valueCount):
try:
n,v,t = EnumValue(aKey,i)
if n == 'ProxyEnable':
return v and True or False
except EnvironmentError:
break
CloseKey(aKey)
def invertProxyEnableState(self):
aReg = ConnectRegistry(None,HKEY_CURRENT_USER)
aKey = OpenKey(aReg, r"Software\Microsoft\Windows\CurrentVersion\Internet Settings", 0, KEY_WRITE)
if self.isProxyEnabled() :
val = 0
else:
val = 1
try:
SetValueEx(aKey,"ProxyEnable",0, REG_DWORD, val)
except EnvironmentError:
print "Encountered problems writing into the Registry..."
CloseKey(aKey)
def updateIcon(self):
if self.isProxyEnabled():
icon=gtk.STOCK_YES
else:
icon=gtk.STOCK_NO
self.trayIcon.set_from_stock(icon)
def checkStatus(self):
self.updateIcon()
return True
def on_right_click(self, data, event_button, event_time):
self.invertProxyEnableState()
self.updateIcon()
if __name__ == '__main__':
proxyNotifier = ProxyNotifier()
gtk.main()
As far as I know, In a Windows environment, if no proxy environment variables are set, proxy settings are obtained from the registry's Internet Settings section. .
Isn't it enough?
Or u can get something useful info from registry:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\ProxyServer
Edit:
sorry for don't know how to format comment's source code, I repost it here.
>>> import win32com.client
>>> js = win32com.client.Dispatch('MSScriptControl.ScriptControl')
>>> js.Language = 'JavaScript'
>>> js.AddCode('function add(a, b) {return a+b;}')
>>> js.Run('add', 1, 2)
3

What Python way would you suggest to check whois database records?

I'm trying to get a webservice up and running that actually requires to check whois databases. What I'm doing right now is ugly and I'd like to avoid it as much as I can: I call gwhois command and parse its output. Ugly.
I did some search to try to find a pythonic way to do this task. Generally I got quite much nothing - this old discussion list link has a way to check if domain exist. Quite not what I was looking for... But still, it was best anwser Google gave me - everything else is just a bunch of unanwsered questions.
Any of you have succeeded to get some method up and running? I'd very much appreciate some tips, or should I just do it the opensource-way, sit down and code something by myself? :)
Found this question in the process of my own search for a python whois library.
Don't know that I agree with cdleary's answer that using a library that wraps
a command is always the best way to go - but I can see his reasons why he said this.
Pro: cmd-line whois handles all the hard work (socket calls, parsing, etc)
Con: not portable; module may not work depending on underlying whois command.
Slower, since running a command and most likely shell in addition to whois command.
Affected if not UNIX (Windows), different UNIX, older UNIX, or
older whois command
I am looking for a whois module that can handle whois IP lookups and I am not interested in coding my own whois client.
Here are the modules that I (lightly) tried out and more information about it:
UPDATE from 2022: I would search pypi for newer whois libraries. NOTE - some APIs are specific to online paid services
pywhoisapi:
Home: http://code.google.com/p/pywhoisapi/
Last Updated: 2011
Design: REST client accessing ARIN whois REST service
Pros: Able to handle IP address lookups
Cons: Able to pull information from whois servers of other RIRs?
BulkWhois
Home: http://pypi.python.org/pypi/BulkWhois/0.2.1
Last Updated: fork https://github.com/deontpearson/BulkWhois in 2020
Design: telnet client accessing whois telnet query interface from RIR(?)
Pros: Able to handle IP address lookups
Cons: Able to pull information from whois servers of other RIRs?
pywhois:
Home: http://code.google.com/p/pywhois/
Last Updated: 2010 (no forks found)
Design: REST client accessing RRID whois services
Pros: Accessses many RRIDs; has python 3.x branch
Cons: does not seem to handle IP address lookups
python-whois (wraps whois command):
Home: http://code.google.com/p/python-whois/
Last Updated: 2022-11 https://github.com/DannyCork/python-whois
Design: wraps "whois" command
Cons: does not seem to handle IP address lookups
whois:
Home: https://github.com/richardpenman/whois (https://pypi.org/project/python-whois/)
Last Updated: 2022-12
Design: port of whois.c from Apple
Cons: TODO
whoisclient - fork of python-whois
Home: http://gitorious.org/python-whois
Last Updated: (home website no longer valid)
Design: wraps "whois" command
Depends on: IPy.py
Cons: does not seem to handle IP address lookups
Update: I ended up using pywhoisapi for the reverse IP lookups that I was doing
Look at this:
http://code.google.com/p/pywhois/
pywhois - Python module for retrieving WHOIS information of domains
Goal:
- Create a simple importable Python module which will produce parsed WHOIS data for a given domain.
- Able to extract data for all the popular TLDs (com, org, net, ...)
- Query a WHOIS server directly instead of going through an intermediate web service like many others do.
- Works with Python 2.4+ and no external dependencies
Example:
>>> import pywhois
>>> w = pywhois.whois('google.com')
>>> w.expiration_date
['14-sep-2011']
>>> w.emails
['contact-admin#google.com',
'dns-admin#google.com',
'dns-admin#google.com',
'dns-admin#google.com']
>>> print w
...
There's nothing wrong with using a command line utility to do what you want. If you put a nice wrapper around the service, you can implement the internals however you want! For example:
class Whois(object):
_whois_by_query_cache = {}
def __init__(self, query):
"""Initializes the instance variables to defaults. See :meth:`lookup`
for details on how to submit the query."""
self.query = query
self.domain = None
# ... other fields.
def lookup(self):
"""Submits the `whois` query and stores results internally."""
# ... implementation
Now, whether or not you roll your own using urllib, wrap around a command line utility (like you're doing), or import a third party library and use that (like you're saying), this interface stays the same.
This approach is generally not considered ugly at all -- sometimes command utilities do what you want and you should be able to leverage them. If speed ends up being a bottleneck, your abstraction makes the process of switching to a native Python implementation transparent to your client code.
Practicality beats purity -- that's what's Pythonic. :)
Here is the whois client re-implemented in Python:
http://code.activestate.com/recipes/577364-whois-client/
I don't know if gwhois does something special with the server output; however, you can plainly connect to the whois server on port whois (43), send your query, read all the data in the reply and parse them. To make life a little easier, you could use the telnetlib.Telnet class (even if the whois protocol is much simpler than the telnet protocol) instead of plain sockets.
The tricky parts:
which whois server will you ask? RIPE, ARIN, APNIC, LACNIC, AFRINIC, JPNIC, VERIO etc LACNIC could be a useful fallback, since they tend to reply with useful data to requests outside of their domain.
what are the exact options and arguments for each whois server? some offer help, others don't. In general, plain domain names work without any special options.
Another way to do it is to use urllib2 module to parse some other page's whois service (many sites like that exist). But that seems like even more of a hack that what you do now, and would give you a dependency on whatever whois site you chose, which is bad.
I hate to say it, but unless you want to re-implement whois in your program (which would be re-inventing the wheel), running whois on the OS and parsing the output (ie what you are doing now) seems like the right way to do it.
Parsing another webpage woulnd't be as bad (assuming their html woulnd't be very bad), but it would actually tie me to them - if they're down, I'm down :)
Actually I found some old project on sourceforge: rwhois.py. What scares me a bit is that their last update is from 2003. But, it might seem as a good place to start reimplementation of what I do right now... Well, I felt obligued to post the link to this project anyway, just for further reference.
here is a ready-to-use solution that works for me; written for Python 3.1 (when backporting to Py2.x, take special care of the bytes / Unicode text distinctions). your single point of access is the method DRWHO.whois(), which expects a domain name to be passed in; it will then try to resolve the name using the provider configured as DRWHO.whois_providers[ '*' ] (a more complete solution could differentiate providers according to the top level domain). DRWHO.whois() will return a dictionary with a single entry text, which contains the response text sent back by the WHOIS server. Again, a more complete solution would then try and parse the text (which must be done separately for each provider, as there is no standard format) and return a more structured format (e.g., set a flag available which specifies whether or not the domain looks available). have fun!
##########################################################################
import asyncore as _sys_asyncore
from asyncore import loop as _sys_asyncore_loop
import socket as _sys_socket
##########################################################################
class _Whois_request( _sys_asyncore.dispatcher_with_send, object ):
# simple whois requester
# original code by Frederik Lundh
#-----------------------------------------------------------------------
whoisPort = 43
#-----------------------------------------------------------------------
def __init__(self, consumer, host, provider ):
_sys_asyncore.dispatcher_with_send.__init__(self)
self.consumer = consumer
self.query = host
self.create_socket( _sys_socket.AF_INET, _sys_socket.SOCK_STREAM )
self.connect( ( provider, self.whoisPort, ) )
#-----------------------------------------------------------------------
def handle_connect(self):
self.send( bytes( '%s\r\n' % ( self.query, ), 'utf-8' ) )
#-----------------------------------------------------------------------
def handle_expt(self):
self.close() # connection failed, shutdown
self.consumer.abort()
#-----------------------------------------------------------------------
def handle_read(self):
# get data from server
self.consumer.feed( self.recv( 2048 ) )
#-----------------------------------------------------------------------
def handle_close(self):
self.close()
self.consumer.close()
##########################################################################
class _Whois_consumer( object ):
# original code by Frederik Lundh
#-----------------------------------------------------------------------
def __init__( self, host, provider, result ):
self.texts_as_bytes = []
self.host = host
self.provider = provider
self.result = result
#-----------------------------------------------------------------------
def feed( self, text ):
self.texts_as_bytes.append( text.strip() )
#-----------------------------------------------------------------------
def abort(self):
del self.texts_as_bytes[:]
self.finalize()
#-----------------------------------------------------------------------
def close(self):
self.finalize()
#-----------------------------------------------------------------------
def finalize( self ):
# join bytestrings and decode them (witha a guessed encoding):
text_as_bytes = b'\n'.join( self.texts_as_bytes )
self.result[ 'text' ] = text_as_bytes.decode( 'utf-8' )
##########################################################################
class DRWHO:
#-----------------------------------------------------------------------
whois_providers = {
'~isa': 'DRWHO/whois-providers',
'*': 'whois.opensrs.net', }
#-----------------------------------------------------------------------
def whois( self, domain ):
R = {}
provider = self._get_whois_provider( '*' )
self._fetch_whois( provider, domain, R )
return R
#-----------------------------------------------------------------------
def _get_whois_provider( self, top_level_domain ):
providers = self.whois_providers
R = providers.get( top_level_domain, None )
if R is None:
R = providers[ '*' ]
return R
#-----------------------------------------------------------------------
def _fetch_whois( self, provider, domain, pod ):
#.....................................................................
consumer = _Whois_consumer( domain, provider, pod )
request = _Whois_request( consumer, domain, provider )
#.....................................................................
_sys_asyncore_loop() # loops until requests have been processed
#=========================================================================
DRWHO = DRWHO()
domain = 'example.com'
whois = DRWHO.whois( domain )
print( whois[ 'text' ] )
import socket
socket.gethostbyname_ex('url.com')
if it returns a gaierror you know know it's not registered with any DNS

Categories