コード例 #1
0
ファイル: views.py プロジェクト: anikal2001/Wowa_backend
def insert_json_data(request):
    data = json.load(request.data.get("File"))
    for value in data:
        serializer = Mortgage_Data_Serializer(data=value)
        if serializer.is_valid():
            serializer.save()
    return Response("200")
コード例 #2
0
ファイル: views.py プロジェクト: simonkorosec/ServeUp
    def cancel_order(self, request):
        """
        Receive order id and delete that order from the database effectively cancelling it.
        Add the order id to the cancelled orders list
        Return conformation of action or error.
        """
        response = {}
        data = json.load(request)
        try:
            order_id = data['id_narocilo']
        except KeyError as e:
            response['status'] = 0
            response['description'] = "Missing key data " + str(e) + ""
            return Response(response, status=status.HTTP_400_BAD_REQUEST)

        # noinspection PyBroadException
        try:
            narocilo = Narocilo.objects.get(id_narocila=order_id)
            order = {'id_narocila': narocilo.id_narocila, 'id_restavracija': narocilo.id_restavracija.id_restavracija}
            narocilo.delete()
            add_cancelled_order(order)
            response['status'] = 1
            response['description'] = "Successfully deleted order"
            return Response(response, status=status.HTTP_200_OK)
        except Exception:
            response['status'] = 0
            response['description'] = "Could not delete order {}".format(order_id)
            return Response(response, status=status.HTTP_503_SERVICE_UNAVAILABLE)
コード例 #3
0
    def handle(self, *args, **options):

        with open('tools/data/%s' % "transport.json") as f:
            data = json.load(f)

        if options['force']:
            TransportType.objects.all().delete()
            TransportMark.objects.all().delete()

        if TransportType.objects.all().count():
            raise ValueError('TransportType is not empty')

        if TransportMark.objects.all().count():
            raise ValueError('TransportMark is not empty')

        t_type = data['type']
        marks = data['marks']

        t_dict = {}

        for t in t_type:
            tt = TransportType.objects.create(name=t['name'])
            t_dict[t['id']] = tt

        for mark_ in marks:
            mark = TransportMark.objects.create(name=mark_['name'])
            for model_ in mark_['models']:
                TransportModel.objects.create(name=model_['name'],
                                              type=t_dict[model_['type']],
                                              mark=mark)
コード例 #4
0
    def json_parsing(self):
        """yogiyo_data_for_parsing.json 파일에서 파싱헤서 DB에 저장"""
        with open('yogiyo_data_for_parsing-final.json', 'r',
                  encoding='utf-8') as file:
            json_data = json.load(file)
        user_list = self.create_users()
        i = 1
        # for restaurant_data in json_data:
        for j in range(126, len(json_data)):
            restaurant_data = json_data[j]
            restaurant_results = restaurant_data['restaurant_results']
            restaurant_info_results = restaurant_data[
                'restaurant_info_results']
            list_info = restaurant_data['list_info']
            review_results = restaurant_data['review_results']
            menu_results = restaurant_data['menu_results']
            avgrating_results = restaurant_data['avgrating_results']

            restaurant = self.restaurant_parsing(restaurant_results,
                                                 restaurant_info_results,
                                                 list_info, avgrating_results)
            self.review_parsing(review_results,
                                restaurant,
                                user_list=user_list)
            self.menu_parsing(menu_results, restaurant)
            print(i)
            i += 1
コード例 #5
0
    def handle(self, *args, **options):
        data = json.load(open(options.get("data"), 'r'))
        bot = SocialBot(json_data=data)

        bot.signup_users()
        bot.login_users()
        bot.create_posts()
コード例 #6
0
 def validate_file(self, file):
     if not file:
         return file
     try:
         self.json_data = json.load(file)
     except:
         raise serializers.ValidationError(_('Bad json file'))
     return file
コード例 #7
0
    def handle(self, *args, **options):
        data = json.load(open(options.get("data"), 'r'))

        bot = Bot(data)
        bot.signup_users()
        bot.login_users()
        bot.create_posts()
        bot.like_time()
コード例 #8
0
    def handle(self, *args, **options):
        data = json.load(open(options.get("data"), 'r'))
        bot = SocialBot(json_data=data)

        bot.signup_users()
        bot.login_users()
        bot.create_posts()

        # Craziness happens when you like someone :)
        bot.like_logic()
コード例 #9
0
ファイル: views.py プロジェクト: simonkorosec/ServeUp
    def new_order(self, request):
        """
        The function receives JSON data with the details of a new order and stores it.
        Return values
        status: 0 - Error, 1 - Successfully added
        description: Short description of Error or confirm desired action
        """
        response = {}
        data = json.load(request)

        try:
            order = {
                "cas_prevzema": data['cas_prevzema'],
                "cas_narocila": data['cas_narocila'],
                "id_restavracija": data['id_restavracija'],
                "id_uporabnik": data['id_uporabnik'],
                "status": ORDER_NEW,
                "checked_in": False
            }
            meals = data['jedi']
        except KeyError as e:
            response['status'] = 0
            response['description'] = "Missing key data " + str(e) + ""
            return Response(response, status=status.HTTP_400_BAD_REQUEST)

        if len(meals) == 0:  # If there are no meals in order wrong formatting
            response['status'] = 0
            response['description'] = "No meal data"
            return Response(response, status=status.HTTP_400_BAD_REQUEST)

        serializer = NarociloSerializer(data=order)
        if serializer.is_valid():
            narocilo = serializer.save()
            id_narocila = narocilo.id_narocila

            success, price = add_meals_to_order(meals, id_narocila)
            if not success:  # Something went wrong delete order
                narocilo.delete()
                response['status'] = 0
                response['description'] = "Could not insert meals"
                return Response(response, status=status.HTTP_400_BAD_REQUEST)

            order['cena'] = price
            order['id_narocila'] = id_narocila
            order['jedi'] = meals
            add_new_order(order)
            response['status'] = 1
            response['description'] = "New order created"
            return Response(response, status=status.HTTP_201_CREATED)
        else:
            response['status'] = 0
            response['description'] = "Could not add new order"
            return Response(response, status=status.HTTP_400_BAD_REQUEST)
コード例 #10
0
    def parse(self, stream, media_type=None, parser_context=None):
        """
        Given a stream to read from, return the parsed representation.
        Should return parsed data, or a `DataAndFiles` object consisting of the
        parsed data and files.
        """
        parser_context = parser_context or {}
        d = parser_context['request']
        # print d.
        encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET)

        try:
            decoded_stream = codecs.getreader(encoding)(stream)

            parse_constant = json.strict_constant if self.strict else None
            print parse_constant, "ffrfrr"
            data = json.load(decoded_stream, parse_constant=parse_constant)
            print data
            return json.load(decoded_stream, parse_constant=parse_constant)
        except ValueError as exc:
            raise ParseError('JSON parse error - %s' % six.text_type(exc))
コード例 #11
0
    def parse(self, stream, media_type=None, parser_context=None):
        """
        Parses the incoming bytestream as JSON and returns the resulting data.
        """
        parser_context = parser_context or {}
        encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET)

        try:
            decoded_stream = codecs.getreader(encoding)(stream)
            parse_constant = json.strict_constant if self.strict else None
            return json.load(decoded_stream, parse_constant=parse_constant)
        except ValueError as exc:
            raise ParseError('JSON parse error - %s' % six.text_type(exc))
コード例 #12
0
    def __init__(self, json_data=None, file_path=None):
        if json_data:
            self.json = json_data
        elif file_path:
            self.json = json.load(open(file_path, 'r'))
        else:
            raise BotNoInitialData("You didn't set json data or path to json.")

        self.number_of_users = self.json['number_of_users'] if self.json.get(
            'number_of_users') else 1
        self.max_posts_per_user = self.json[
            'max_posts_per_user'] if self.json.get('max_posts_per_user') else 1
        self.max_likes_per_user = self.json[
            'max_likes_per_user'] if self.json.get('max_likes_per_user') else 1
コード例 #13
0
def dashboard_choose_view(request):

    if request.method == "POST":

        return redirect('../status/')

        # video = VideoForm(request.POST, request.FILES)
        # if video.is_valid():
        #     current_user_id = request.user.id
        #     handle_uploaded_file(request.FILES['video'], request.POST.get('codigo'), current_user_id)
        #     print("File uploaded successfuly")
        #     HttpResponse("File uploaded successfuly")
        #     return redirect('../choose/')

    elif request.method == "GET":
        # Variables de dashboard
        user_name = str(request.user.username)
        client = MongoClient(key_3)
        db = client.galeria
        collection = db.videos

        list_filename_temp = []
        current_user_id = request.user.id
        myvideos = collection.find({'current_user_id': str(current_user_id)})

        for myvid in myvideos:
            list_filename_temp.append(myvid['static_file_dir'])
        try:
            last_video = list_filename_temp[-1]
        except Exception as e:
            last_video = str(e)

        # list_filename_temp

        # # GET CHUNKS OF THE FILE WITH ID
        # print("GET CHUNKS OF THAT FILE")
        # files_id = ObjectId('5f67ee7920bfdaf148938ccd')
        # thefile = []
        # for chunk in cluster_db['uploaded_videos']['chunks'].find({"files_id": files_id}):
        #     thefile.append(chunk['data'])
        #     pprint.pprint(chunk['_id'])

        with open("models.json", encoding='utf-8', errors='ignore') as json_data:
            myjson = json.load(json_data, strict=False)

        return render(request, 'dashboard/pipeline/choose.html', locals())
コード例 #14
0
    def import_entries(self, options):
        with transaction.atomic():
            with smart_open(options['target_file'], 'r') as fp:
                entries = json.load(fp)

                gene_list = options['genes'].split(
                    ",") if options['genes'] else None

                for entry in entries:
                    # skip entries not mentioned in the gene list
                    if gene_list and entry['variant'][
                            'gene__symbol'] not in gene_list:
                        continue

                    create_entry_from_fields(entry)

                self.stdout.write(
                    self.style.SUCCESS('Read %d entries from source file' %
                                       len(entries)))
コード例 #15
0
ファイル: initdb.py プロジェクト: Pitt-Pauly/Astrosat_test
    def handle(self, *args, **options):
        # go through json and for each object in list, validate data via serializer, and save object.
        filepath = self.default_file
        if options['filepath']:
            filepath = options['filepath']

        if filepath is None or filepath == '':
            raise CommandError(
                'No filepath given and default filepath could not be retrieved from the settings. '
                'is INIT_DB_DEFAULT_JSON set?'
            )

        self.stdout.write(self.style.NOTICE('Loading JSON data from file %s into database...' % filepath))

        with open(filepath) as f:
            data = json.load(f)
            serializer = FacilitySerializer(data=data, many=True)
            if serializer.is_valid(raise_exception=True):
                serializer.save()
                self.stdout.write(self.style.SUCCESS('Successfully initialized Database with JSON'))
コード例 #16
0
    def handle(self, *args, **options):
        countries = (
            'kazakstan.json',
            'russian.json',
            'kyrgyzstan.json',
            'armeniya.json',
            'uzbekistan.json',
            'azerbaijan.json',
            'gruziya.json',
            'belarus.json',
            'turkmenistan.json',
            'moldaviya.json',
            'tadjikistan.json',
            'ukraine.json',
        )

        for file in countries:
            with open('tools/data/%s' % file) as f:
                country_ = json.load(f)

            if options['force']:
                Country.objects.filter(name=country_["name"]).delete()

            if Country.objects.filter(name=country_["name"]).count():
                if options['ignore']:
                    continue
                raise ValueError('Country %s already exist' % country_["name"])

            country = Country.objects.create(name=country_["name"],
                                             phone_code="+7",
                                             phone_mask="todo")
            for region_ in country_["children"]:
                region = Region.objects.create(name=region_["name"],
                                               country=country)
                for city_ in region_["children"]:
                    City.objects.create(name=city_, region=region)
コード例 #17
0
ファイル: autoMode.py プロジェクト: Brisseta/SmartHome
import os
import time
from typing import Any

from polling import poll, TimeoutException
from rest_framework.utils import json

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Batz.settings")
from django.core.wsgi import get_wsgi_application

application = get_wsgi_application()
import Batz_API
from Batz_API.models import Trigger, TriggerLog

with open('ressouces.json', 'r') as f:
    ressource_json = json.load(f)


class AutoMode():
    def __init__(self, automode_status):
        self.name = "Automode"
        self.automode_status = automode_status
        self.triggers = Batz_API.models.Trigger.objects
        self.relai1_obj = self.triggers.get(trigger_name='relai1')
        self.relai2_obj = self.triggers.get(trigger_name='relai2')
        self.thermostat_obj = self.triggers.get(trigger_name='termostat')
        self.timer1_obj = self.triggers.get(trigger_name='timer1')
        self.timer2_obj = self.triggers.get(trigger_name='timer2')
        self.chauffage_status_obj = self.triggers.get(trigger_name='chauffage')

    # def start(self):