Exemple #1
0
def genera_pases(partido):
	arc = open('data/pases_' + str(partido.pk) + '.csv', 'w')

	json = simplejson.loads(partido.json)
	pases, malas = {}, {}
	for jugador in Jugador.objects.filter(equipo__in = partido.equipos.all()):
		pases[jugador.pk] = 0
		malas[jugador.pk] = 0
	for jugada in json:
		""" Calcula pases y jugadas malas por jugador """
		timestamp, periodo, de, a, contexto, saque = jugada
		if de and a:
			de = Jugador.objects.get(pk=de)
			a  = Jugador.objects.get(pk=a )
			if de.equipo == a.equipo:
				""" Pase bueno """
				pases[de.pk] += 1
			else:
				""" Pelota perdida """
				malas[de.pk] += 1

	for pk in pases:
		jugador = Jugador.objects.get(pk=pk)
		arc.write(','.join([
			str(pk),
			str(pases[pk]),
			str(malas[pk]),
			])+'\n')

	arc.close()
Exemple #2
0
def handle_login(request):
    csrf_middleware = CsrfViewMiddleware()

    response_data = {}
    form = None

    if request.raw_post_data:
        request.POST = json.loads(request.raw_post_data)
        csrf_middleware.process_view(request, None, None, None)
        if 'data' in request.POST:
            form = LoginForm(data=request.POST['data'])
            if form.is_valid():
                if not request.POST['meta']['validate']:
                    auth_login(request, form.get_user())
    else:
        form = LoginForm(request)
        response_data['csrfmiddlewaretoken'] = get_token(request)

    if form is not None:
        remote_form = RemoteForm(form)
        response_data.update(remote_form.as_dict())

    response = HttpResponse(json.dumps(response_data, cls=LazyEncoder),
                            mimetype="application/json")
    csrf_middleware.process_response(request, response)
    return response
def handle_login(request):
    csrf_middleware = CsrfViewMiddleware()

    response_data = {}
    form = None

    if request.raw_post_data:
        request.POST = json.loads(request.raw_post_data)
        csrf_middleware.process_view(request, None, None, None)
        if 'data' in request.POST:
            form = LoginForm(data=request.POST['data'])
            if form.is_valid():
                if not request.POST['meta']['validate']:
                    auth_login(request, form.get_user())
    else:
        form = LoginForm(request)
        response_data['csrfmiddlewaretoken'] = get_token(request)

    if form is not None:
        remote_form = RemoteForm(form)
        response_data.update(remote_form.as_dict())

    response = HttpResponse(json.dumps(response_data, cls=LazyEncoder), mimetype="application/json")
    csrf_middleware.process_response(request, response)
    return response
 def wrapper(request, *args, **kwargs):
     request.JSON = {}
     content_type = request.META.get('CONTENT_TYPE', 'text/plain')
     request.is_json = True if 'application/json' in content_type else False
     if (request.method == 'POST' and request.is_json):
         try:
             data = json.loads(request.raw_post_data)
         except ValueError:
             return HttpResponseBadRequest()
         request.JSON = data
     return func(request, *args, **kwargs)
Exemple #5
0
def genera_jugadas(partido):
	arc = open('data/jugadas_' + str(partido.pk) + '.csv', 'w')
	json = simplejson.loads(partido.json)
	for j in json:
		x = [
			str(j[0]),
			'1' if j[1] else '0',
			str(j[2]) if j[2] else '0', 
			str(j[3]) if j[3] else '9',
			j[4] if j[4] else '',
			'1' if j[5] else '0']
		arc.write(','.join(['"'+e+'"' for e in x]) + '\n')
	arc.close()
Exemple #6
0
 def to_json_structure(self, accept=DEFAULT_ACCEPT):
     r = {
         'id': self.id,
         'jurisdiction': self.jurisdiction,
         'Geometry': json.loads(self.geom.geojson)
     }
     for field in serialization.ELEMENTS:
         if field.type == 'TEXT':
             val = self.get_text_value(field.tag, accept=accept)
         else:
             val = self.xml_elem.xpath(field.tag + '/text()')
             val = val[0] if val else None
         if val not in [None, '']:
             r[field.tag] = val
     return r
def get_video_info(video_id):
    """
    Return a dict with the info of a given video
    :param video_id: the vimeo video ID
    :return: a dict object with the data described at
    """
    cache_key = "vimeo-video-id-{}".format(video_id)
    info = cache.get(cache_key)
    if info is not None:
        return info
    res = requests.get(VIDEO_ENDPOINT.format(video=video_id))
    if not res.ok:
        res.raise_for_status()
    info = simplejson.loads(res.content)[0]
    cache.set(cache_key, info)
    return info
    def serialize(self, raw_post_data):
        # json_str = raw_post_data.keys()[0]
        # post_data = decode(json_str)
        post_data = simplejson.loads(raw_post_data)
        request_id = post_data.get("id", 0)
        request_method = post_data.get("method")
        request_params = post_data.get("params", [])
        response = {"id": request_id}

        try:
            response.__setitem__("result", self.dispatch(request_method, request_params))
        except:
            if self.allow_errors:
                from sys import exc_type, exc_value

                response.__setitem__("error", "%s: %s" % (exc_type, exc_value))
                response.__setitem__("result", None)
            else:
                response.__setitem__("error", "error")
                response.__setitem__("result", None)
        return response
    def authenticate(self, token=None):

        api_sig = md5("api_key%smethodauth.getSessiontoken%s%s" % (API_KEY, token, SECRET)).hexdigest()

        get_session_url = "%s?method=auth.getSession&token=%s&api_key=%s&api_sig=%s&format=json" % (
            WS_URL,
            token,
            API_KEY,
            api_sig,
        )

        try:
            session_data = urlopen(get_session_url).read()
            session_dict = simplejson.loads(session_data)
            user_dict = session_dict["session"]
        except:
            # couln't authenticate against lastfm api
            return None

        # try to find a user instance with a matching lastfm profile,
        # otherwise we create it:
        user, user_created = User.objects.get_or_create(
            lastfmprofile__name=user_dict["name"], defaults={"username": user_dict["name"]}
        )

        if user_created:
            user.set_password(User.objects.make_random_password())
            user.save()

            # then we must create a lastfm profile...
            profile, profile_created = LastfmProfile.objects.get_or_create(
                name=user_dict["name"],
                defaults={"key": user_dict["key"], "is_subscriber": int(user_dict["subscriber"]), "user": user},
            )

        # else:
        # FIXME:
        # should we update key session? and user info?

        return user
    def authenticate(self, token=None):

        api_sig = md5("api_key%smethodauth.getSessiontoken%s%s"\
            % (API_KEY, token, SECRET)).hexdigest()

        get_session_url = "%s?method=auth.getSession&token=%s&api_key=%s&api_sig=%s&format=json"\
            % (WS_URL, token, API_KEY, api_sig)

        try:
            session_data = urlopen(get_session_url).read()
            session_dict = simplejson.loads(session_data)
            user_dict = session_dict["session"]
        except:
            # couln't authenticate against lastfm api
            return None

        # try to find a user instance with a matching lastfm profile,
        # otherwise we create it:
        user, user_created = User.objects.get_or_create(
            lastfmprofile__name=user_dict["name"],
            defaults={"username": user_dict["name"]})

        if user_created:
            user.set_password(User.objects.make_random_password())
            user.save()

            # then we must create a lastfm profile...
            profile, profile_created = LastfmProfile.objects.get_or_create(
                name=user_dict["name"],
                defaults={
                    "key": user_dict["key"],
                    "is_subscriber": int(user_dict["subscriber"]),
                    "user": user
                })

        # else:
        # FIXME:
        # should we update key session? and user info?

        return user
Exemple #11
0
def json_topic_form(request):
    csrf_middleware = CsrfViewMiddleware()

    response_data = {}
    if request.method == 'GET':
        form = TopicForm()
    elif request.raw_post_data:
        request.POST = json.loads(request.raw_post_data)

        csrf_middleware.process_view(request, None, None, None, None)
        form_data = request.POST.get('data', {})
        form = TopicForm(form_data)
        if form.is_valid():
            form.save()

    remote_form = RemoteForm(form)

    response_data.update(remote_form_as_dict())

    response = HttpResponse(json.dumps(response_data, cls=DjangoJSONEncoder), mimetype='application/json')

    csrf_middleware.process_response(request, response)
    return response;
Exemple #12
0
 def get_data(self):
     return simplejson.loads(self._data)
Exemple #13
0
def handle_instance_form(request, app_label, model_name, instance_id=None):
    if not request.user.is_authenticated():
        return HttpResponse('Unauthorized', status=401)

    csrf_middleware = CsrfViewMiddleware()

    response_data = {
        'meta': {
            'app_label': app_label,
            'model_name': model_name
        },
        'admin': {}
    }

    instance = None

    for model, model_admin in site._registry.items():
        if app_label != model._meta.app_label or model_name != model._meta.module_name:
            continue

        field_configuration = {
            'include': model_admin.fields or [],
            'exclude': model_admin.exclude or [],
            'ordering': model_admin.fields or [],
            'fieldsets': model_admin.fieldsets or {},
            'readonly': model_admin.readonly_fields or []
        }

        if instance_id is not None:
            response_data[instance_id] = instance_id
            try:
                instance = model.objects.get(pk=instance_id)
            except model.DoesNotExist:
                raise Http404('Invalid instance ID')

        current_model = model

        CurrentModelForm = ADMIN_FORM_OVERRIDES.get(model_name, None)

        if CurrentModelForm is None:

            class CurrentModelForm(ModelForm):
                class Meta:
                    model = current_model

        if request.method == 'GET':
            # Return instance form for given model name
            # Return initial values if instance ID is supplied, otherwise return empty form
            if instance is None:
                form = CurrentModelForm()
            else:
                form = CurrentModelForm(instance=instance)
                for field_name, initial_value in form.initial.items():
                    if initial_value is not None and field_name in form.fields:
                        form.fields[field_name].initial = initial_value

            response_data['csrfmiddlewaretoken'] = get_token(request)

            remote_form = RemoteForm(form, **field_configuration)
            response_data.update(remote_form.as_dict())
        elif request.raw_post_data:
            request.POST = json.loads(request.raw_post_data)
            csrf_middleware.process_view(request, None, None, None)
            if 'data' in request.POST:
                if instance_id is None:
                    form = CurrentModelForm(request.POST['data'])
                else:
                    form = CurrentModelForm(request.POST['data'],
                                            instance=instance)
                if form.is_valid():
                    if not request.POST['meta']['validate']:
                        form.save()

                remote_form = RemoteForm(form, **field_configuration)
                response_data.update(remote_form.as_dict())

    response = HttpResponse(json.dumps(response_data, cls=LazyEncoder),
                            mimetype="application/json")
    csrf_middleware.process_response(request, response)
    return response
def handle_instance_form(request, app_label, model_name, instance_id=None):
    if not request.user.is_authenticated():
        return HttpResponse('Unauthorized', status=401)

    csrf_middleware = CsrfViewMiddleware()

    response_data = {
        'meta': {
            'app_label': app_label,
            'model_name': model_name
        },

        'admin': {}
    }

    instance = None

    for model, model_admin in site._registry.items():
        if app_label != model._meta.app_label or model_name != model._meta.module_name:
            continue

        field_configuration = {
            'include': model_admin.fields or [],
            'exclude': model_admin.exclude or [],
            'ordering': model_admin.fields or [],
            'fieldsets': model_admin.fieldsets or {},
            'readonly': model_admin.readonly_fields or []
        }

        if instance_id is not None:
            response_data[instance_id] = instance_id
            try:
                instance = model.objects.get(pk=instance_id)
            except model.DoesNotExist:
                raise Http404('Invalid instance ID')

        current_model = model

        CurrentModelForm = ADMIN_FORM_OVERRIDES.get(model_name, None)

        if CurrentModelForm is None:
            class CurrentModelForm(ModelForm):
                class Meta:
                    model = current_model

        if request.method == 'GET':
            # Return instance form for given model name
            # Return initial values if instance ID is supplied, otherwise return empty form
            if instance is None:
                form = CurrentModelForm()
            else:
                form = CurrentModelForm(instance=instance)
                for field_name, initial_value in form.initial.items():
                    if initial_value is not None and field_name in form.fields:
                        form.fields[field_name].initial = initial_value

            response_data['csrfmiddlewaretoken'] = get_token(request)

            remote_form = RemoteForm(form, **field_configuration)
            response_data.update(remote_form.as_dict())
        elif request.raw_post_data:
            request.POST = json.loads(request.raw_post_data)
            csrf_middleware.process_view(request, None, None, None)
            if 'data' in request.POST:
                if instance_id is None:
                    form = CurrentModelForm(request.POST['data'])
                else:
                    form = CurrentModelForm(request.POST['data'], instance=instance)
                if form.is_valid():
                    if not request.POST['meta']['validate']:
                        form.save()

                remote_form = RemoteForm(form, **field_configuration)
                response_data.update(remote_form.as_dict())

    response = HttpResponse(json.dumps(response_data, cls=LazyEncoder), mimetype="application/json")
    csrf_middleware.process_response(request, response)
    return response
Exemple #15
0
 def get_data(self):
     return simplejson.loads(self._data)
from django.core.serializers.json import simplejson
from urllib import urlopen
import time, datetime
from threequarters.blog.models import Twitter

url = 'http://twitter.com/statuses/user_timeline/rodbegbie.json?count=500'
json = urlopen(url).read()

for entry in simplejson.loads(json):
    desc = entry["text"].encode('utf-8')
    desc = desc.replace(""", '"')
    desc = desc.replace("&", '&')
    print desc
    (twitter, new) = Twitter.objects.get_or_create(twitter_id = entry["id"])
    if new or twitter.description != desc:
    	twitter.description = desc
        twitter.created_on = datetime.datetime(*(time.strptime(entry["created_at"], "%a %b %d %H:%M:%S +0000 %Y")[0:6])) - datetime.timedelta(hours=8)
        twitter.save()