Check some part of string in variable in template Django - python

Hi i got the site domain in the template name with the
{{request.META.HTTP_HOST}}
from which i got the value some thing like this
pydev.aviesta.com
and
pydev.aviesta.com.mx
i need to show different data for both domains but as this is the dev server i cant use the full doamin name for compare can i check only .mx or .com so there will be no problem when going to live site

You may need Custom filter for this.
#register.filter(name='split')
def split(value, arg):
return value.split('.')[-1]
Use it as {{request.META.HTTP_HOST|split}}

i got the solution with js
<script>
var str = location.host;
if( str.search(".mx") > 0 ){
var dom = 'mx';
}else{
var dom = 'com';
} </script>

Related

How to replace get_declared_classes() from CakePHP to Python?

I have been moving website made in Cakephp into Django. In one place I found get_declared_classes(). I thinks this function returns list of previously used classes before running current class.
First time when I encounter this, I just store list of classes manually in one file and I was using that and this solution worked only for a particular web page but Now I have multiple pages calling this class and everytime list of classnames are very different so I can not store class name list.
This code is actually connecting and fetching data from here and I want to replace this class in python(We are replacing whole website). The only problem I have is how to replace get_declared_classes.
class HrbcConnect{
private $scope = '';
private $token = null;
private $token_expire = 0;
private $request_opt = array();
public $id;
public $id_arr = array();
public $write_error;
public function read($resource,$condition='',$field=array(),$order=null){
$declared_classes = get_declared_classes();
foreach(App::objects('Model') as $v){
if(in_array($v,$declared_classes)){
$instance = new $v;
if(property_exists($instance,'hrbc_cols') && array_key_exists(ucfirst($resource),$instance->hrbc_cols)){
foreach($instance->hrbc_cols[ucfirst($resource)] as $vv){
if(is_array($vv)){
$field[] = $vv[0];
}else{
$field[] = $vv;
}
}
}elseif(property_exists($instance,'hrbc_cols_arr')){
foreach($instance->hrbc_cols_arr as $kk=>$vv){
if(array_key_exists(ucfirst($resource),$vv)){
foreach($vv[ucfirst($resource)] as $vvv){
if(is_array($vvv) && !in_array($vvv[0],$field)){
$field[] = $vvv[0];
}elseif(!is_array($vvv) && !in_array($vvv,$field)){
$field[] = $vvv;
}
}
}
}
}
}
}
}
}
When I print the $v in the above code to find what are classes being used, I found list of classes that defined in my models.
If question is not clear please let me know, I can provide more information.
Is there any other library that can replace this function in Python? Or Is there any other solution I can try ?

How do I block the IP for those who enter my website twice?

I have this code:
$accounts = fopen("accounts.txt", "r+");
$give_account = fgets($accounts);
$fileContents = file_get_contents("ips.txt");
fclose($accounts);
if(strpos($fileContents, $ip) !== false){
echo $give_account;
}else{
echo "you have already received an account";
}
i want to get his ip(i got this point),and I want you to receive your account,and I want to delete from the list the account that I gave and not be able to receive another one and print the else.If you can help me with something, even a little, I would appreciate it.Thanks
Imagining that you do not have any kind of database usage in your website, This code should give you a quick heads up on how to handle your scenario.
TIP: Try not to parse files like strings. Instead, use JSON or XML or some kind of markup language.
<?php
if(!function_exists('get_client_ip')){
function get_client_ip() {
$ipaddress = '';
if (isset($_SERVER['HTTP_CLIENT_IP']))
$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_X_FORWARDED']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED'];
else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_FORWARDED']))
$ipaddress = $_SERVER['HTTP_FORWARDED'];
else if(isset($_SERVER['REMOTE_ADDR']))
$ipaddress = $_SERVER['REMOTE_ADDR'];
else
$ipaddress = null;
return $ipaddress;
}
}
if(!function_exists('log_ip_address')){
function log_ip_address($ip, $account_id){
// Get the JSON object from the IP Logs file and add this IP to the object
// $ip_logged is true if JSON object is updated. false otherwise
$ip_logged = true;
return $ip_logged ? true : false;
}
}
if(!function_exists('allot_account_to_client')){
function allot_account_to_client($account_id, $ip){
if(empty($account_id) || empty($ip)){
throw new Exception("Parameter missing");
}
// Do your magic here and allot an account to your client if he deserves
$alloted = true;
// When alloted, remove the current $account_id from the accounts JSON objects so that you won't allot the same account_id to anyone else
// Log the IP address
$log = log_ip_address($ip, $account_id);
// return true only if ip is logged. If IP logging fails, write a mechanism to put back the account_id back to the accounts Array.
return $log ? true : false;
}
}
$ip = get_client_ip();
if($ip == null){
throw new Exception("Unable to get IP. Do you even exist?");
}
// contains an JSON object of IP addresses that an account was taken from and it's details
$list_of_ips = json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'].'/logs/ips.json'));
// Contains JSON Array of account_ids
$accounts = json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'].'/accounts/available_accounts.json'));
if(isset($list_of_ips[$ip])){
$taken_on = new DateTime($list_of_ips[$ip]['taken_on']);
throw new Exception("You already got your account on ".$taken_on->format('m-d-Y H:i:sP'));
}
$available_account_id = $accounts[0];
// If he comes until here, he deserves the account
$alloted = allot_account_to_client($account_id, $ip);
if(!$alloted){
echo "Unable to allot you an account.";
exit(0);
}
echo "Your account id is : ".$account_id;
?>
EDIT:
I do not suggest you to use the files located in your server like this as these files are accessible to the user and it compromises whatever you are doing. Use Databases instead.
If you are so determined to use the files, instead of storing the unencrypted data, use some encryption methods to encrypt the data so that at least a normal non techie user would not know what it is.
You can write the IPs from the visitor in a local-file on your server. If someone visits your site, read this file either complete as an array in and check with array_key_exists if this IP is inside your list (compare with !== -1 for exists) or read line by line in and check if they are equal.
If the IP is twice then you can make a redirect to another site perhaps something like "Upps, your here again. I only like new vistors" or you just put the whole following code in an if-block that it won't be evaluated.

How to get the data submitted using POST on Python using Pyramid?

I'm looking for the equivalent of PHP's $_POST[] in Python.
On PHP, when you submit a form you can get its value by using the $_POST[].
How can I get this data on python?
here is my code.
function NewUser(){
var firstName = $('#firstName').val();
var dataString = '&firstName='+firstName;
$.ajax({
type:"POST",
url:"newusers",
data:dataString,
dataType:'text',
success:function(s){
alert(s);
},
error:function(){
alert('FAILED!');
}
})
}
This is where I throw the data.
#view_config(route_name='newusers', renderer='json')
def newusers(self):
return '1';
This code works fine and it returns and alert a string "1".
My question is, how can I get the submitted firstName? and put it on the return instead of "1".
Thank you in advance!
Another variation that should work:
#view_config(route_name='newusers', renderer='json')
def newusers(self):
# Best to check for the case of a blank/unspecified field...
if ('firstName' in self.request.params):
name = str(self.request.params['firstName'])
else:
name = 'null'
return name
Note: Be careful using str() function, particularly in python 2.x, as it may not be compatible with unicode input using characters beyond ascii. You might consider:
name = (self.request.params['firstName']).encode('utf-8')
as an alternative.
I manage to make it work with this code.
#view_config(route_name='newusers', renderer='json')
def newusers(self):
name = str(self.request.POST.get('firstName'))
return name

Openerp information messages

Is it possible to create information message with options like proceed or cancel in OpenERP ? If it is possible how to create one ?
You can extend a js web module to do that.
Create script.js under /module_name/static/src/js/ which contains:
openerp.module_name = function(instance) {
var _t = instance.web._t,
_lt = instance.web._lt;
var QWeb = instance.web.qweb;
/* For example */
instance.web.FormView.include({
});
};
You can create a wizard with cancel and proceed button within

jQuery getJSON Output using Python/Django

So, I'm trying to make a simple call using jQuery .getJSON to my local web server using python/django to serve up its requests. The address being used is:
http://localhost:8000/api/0.1/tonight-mobile.json?callback=jsonp1290277462296
I'm trying to write a simple web view that can access this url and return a JSON packet as the result (worried about actual element values/layout later).
Here's my simple attempt at just alerting/returning the data:
$.getJSON("http://localhost:8000/api/0.1/tonight-mobile.json&callback=?",
function(json){
alert(json);
<!--$.each(json.items, function(i,item){
});-->
});
I am able to access this URL directly, either at http://localhost:8000/api/0.1/tonight-mobile.json or http://localhost:8000/api/0.1/tonight-mobile.json&callback=jsonp1290277462296 and get back a valid JSON packet... So I'm assuming it's in my noob javascript:)
My views.py function that is generating this response looks as follows:
def tonight_mobile(request):
callback = request.GET.get('callback=?', '')
def with_rank(rank, place):
return (rank > 0)
place_data = dict(
Places = [make_mobile_place_dict(request, p) for p in Place.objects.all()]
)
xml_bytes = json.dumps(place_data)
xml_bytes = callback + '(' + xml_bytes + ');'
return HttpResponse(xml_bytes, mimetype="application/json")
With corresponding urls.py configuration:
(r'^tonight-mobile.json','iphone_api.views.tonight_mobile'),
I am still somewhat confused on how to use callbacks, so maybe that is where my issue lies. Note I am able to call directly a 'blah.json' file that is giving me a response, but not through a wired URL. Could someone assist me with some direction?
First, callback = request.GET.get('callback=?', '') won't get you the value of callback.
callback = request.GET.get( 'callback', None )
Works much better.
To debug this kind of thing. You might want to include print statements in your Django view function so you can see what's going on. For example: print repr(request.GET) is a helpful thing to put in a view function so that you can see the GET dictionary.

Categories