import json
from urllib2 import Request, urlopen

from django.db import models
from passerelle.base.models import BaseResource

class BaseRepost(BaseResource):
    url = models.CharField(max_length=200)
    timeout = models.IntegerField(null=True, blank=True)

    def repost(self, data, **kwargs):
        r = Request(self.url)
        r.add_header('Accept', 'application/json')
        r.add_header('Content-Type', 'application/json;charset=UTF-8')
        r.add_data(json.dumps(data))
        if self.timeout:
            p = urlopen(r, timeout=self.timeout)
        else:
            p = urlopen(r)
        out_data = json.loads(p.read())
        p.close()
        return out_data
