Jump to content
Korean Random
Aydomir

HTTP запрос, JSON

Recommended Posts

Помогите как сделать http-запрос на любой url, затем получить данные с помощью JSON и вывести полученный текст?

 

Мне удалось по-примеру создать сообщение в Центре Уведомлений, где "Text Message" должна быть полученный со сервера текст. Это все для примера.

 

VG2Jkq_e2Fs.jpg

Share this post


Link to post

Short link
Share on other sites
from urllib import urlopen
from json import load

obj = load(urlopen('http://**********/test.json'))
print(obj['items']['item1'])

test.json

{
   "items": {
      "item1":"Test item"
   }
}
Edited by ShadowHunterRUS

Share this post


Link to post

Short link
Share on other sites
from urllib import urlopen
import json

text = urlopen('http://**********/test.json').read()
obj = json.parse(text)
print(obj['items']['item1'])
test.json

{
   "items": {
      "item1":"Test item"
   }
}
from notification.NotificationListView import NotificationListView

old_populate = NotificationListView._populate

def new_populate(self):
    message = {
        'typeID': 1,
        'message': {
            'bgIcon': '',
            'defaultIcon': '',
            'savedData': 0,
            'timestamp': -1,
            'filters': [],
            'buttonsLayout': [
                {
                    'action': 'action_1',
                    'type': 'submit',
                    'label': 'Button 1'
                },
                {
                    'action': 'action_2',
                    'type': 'submit',
                    'label': 'Button 2'
                }
            ],
            'message': 'Test Message',
            'type': 'black',
            'icon': '',
        },
        'entityID': 99999,
        'auxData': ['GameGreeting']
    }
    old_populate(self)
    self.as_appendMessageS(message)

NotificationListView._populate = new_populate

old_onClickAction = NotificationListView.onClickAction

def new_onClickAction(self, typeID, entityID, action):
    if action == 'action_1':
        print 'action_1'
    elif action == 'action_2':
        print 'action_2'
    else:
        old_onClickAction(self, typeID, entityID, action)

NotificationListView.onClickAction = new_onClickAction

Вот код, который я пользуюсь для примера. Можете совместить? Я раньше не писал на питоне, поэтому не уверен в себе.

Share this post


Link to post

Short link
Share on other sites


from BigWorld import wg_openWebBrowser
from urllib import urlopen
import json
text = urlopen('http://**********/test.json').read()
obj = json.parse(text)
print(obj['items']['item1'])

from notification.NotificationListView import NotificationListView
old_populate = NotificationListView._populate
def new_populate(self):
    message = {
        'typeID': 1,
        'message': {
            'bgIcon': '',
            'defaultIcon': '',
            'savedData': 0,
            'timestamp': -1,
            'filters': [],
            'buttonsLayout': [
                {
                    'action': 'action_1',
                    'type': 'submit',
                    'label': 'Button 1'
                },
                {
                    'action': 'action_2',
                    'type': 'submit',
                    'label': 'Button 2'
                }
            ],
            'message': obj['items']['item1'],
            'type': 'black',
            'icon': '',
        },
        'entityID': 99999,
        'auxData': ['GameGreeting']
    }
    old_populate(self)
    self.as_appendMessageS(message)
NotificationListView._populate = new_populate
old_onClickAction = NotificationListView.onClickAction


def new_onClickAction(self, typeID, entityID, action):
    if action == 'action_1':
        print 'action_1'
wg_openWebBrowser(http://www.yandex.ru/)
    elif action == 'action_2':
        print 'action_2'
    else:
        old_onClickAction(self, typeID, entityID, action)
NotificationListView.onClickAction = new_onClickAction

 

Edited by Dark_Knight_MiX

Share this post


Link to post

Short link
Share on other sites

Можете совместить?

from notification.NotificationListView import NotificationListView
from urllib import urlopen
from json import load
 
try:
   obj = load(urlopen('http://<some_url>/test.json'))
except Exception:
   obj = {u'items':{u'item1':'Error in get file!'}}
 
old_populate = NotificationListView._populate
def new_populate(self):
    message = {
        'typeID': 1,
        'message': {
            'bgIcon': '',
            'defaultIcon': '',
            'savedData': 0,
            'timestamp': -1,
            'filters': [],
            'buttonsLayout': [
                {
                    'action': 'action_1',
                    'type': 'submit',
                    'label': 'Button 1'
                },
                {
                    'action': 'action_2',
                    'type': 'submit',
                    'label': 'Button 2'
                }
            ],
            'message': obj['items']['item1'],
            'type': 'black',
            'icon': '',
        },
        'entityID': 99999,
        'auxData': ['GameGreeting']
    }
    old_populate(self)
    self.as_appendMessageS(message)
NotificationListView._populate = new_populate
old_onClickAction = NotificationListView.onClickAction
def new_onClickAction(self, typeID, entityID, action):
    if action == 'action_1':
        print 'action_1'
    elif action == 'action_2':
        print 'action_2'
    else:
        old_onClickAction(self, typeID, entityID, action)
NotificationListView.onClickAction = new_onClickAction
Edited by ShadowHunterRUS

Share this post


Link to post

Short link
Share on other sites
from BigWorld import wg_openWebBrowser
from urllib import urlopen
import json
text = urlopen('http://**********/test.json').read()
obj = json.parse(text)
print(obj['items']['item1'])

from notification.NotificationListView import NotificationListView
old_populate = NotificationListView._populate
def new_populate(self):
    message = {
        'typeID': 1,
        'message': {
            'bgIcon': '',
            'defaultIcon': '',
            'savedData': 0,
            'timestamp': -1,
            'filters': [],
            'buttonsLayout': [
                {
                    'action': 'action_1',
                    'type': 'submit',
                    'label': 'Button 1'
                },
                {
                    'action': 'action_2',
                    'type': 'submit',
                    'label': 'Button 2'
                }
            ],
            'message': obj['items']['item1'],
            'type': 'black',
            'icon': '',
        },
        'entityID': 99999,
        'auxData': ['GameGreeting']
    }
    old_populate(self)
    self.as_appendMessageS(message)
NotificationListView._populate = new_populate
old_onClickAction = NotificationListView.onClickAction
def new_onClickAction(self, typeID, entityID, action):
    if action == 'action_1':
        print 'action_1'
        wg_openWebBrowser(http://www.yandex.ru/)  
    elif action == 'action_2':
        print 'action_2'
    else:
        old_onClickAction(self, typeID, entityID, action)
NotificationListView.onClickAction = new_onClickAction

 

 

from notification.NotificationListView import NotificationListView
from urllib import urlopen
from json import loads
 
try:
   text = urlopen('http://**********/test.json').read()
   obj = loads(text)
except Exception:
   obj = {"items":{ "item1":"Error in get file!" }}
 
old_populate = NotificationListView._populate
def new_populate(self):
    message = {
        'typeID': 1,
        'message': {
            'bgIcon': '',
            'defaultIcon': '',
            'savedData': 0,
            'timestamp': -1,
            'filters': [],
            'buttonsLayout': [
                {
                    'action': 'action_1',
                    'type': 'submit',
                    'label': 'Button 1'
                },
                {
                    'action': 'action_2',
                    'type': 'submit',
                    'label': 'Button 2'
                }
            ],
            'message': obj['items']['item1'],
            'type': 'black',
            'icon': '',
        },
        'entityID': 99999,
        'auxData': ['GameGreeting']
    }
    old_populate(self)
    self.as_appendMessageS(message)
NotificationListView._populate = new_populate
old_onClickAction = NotificationListView.onClickAction
def new_onClickAction(self, typeID, entityID, action):
    if action == 'action_1':
        print 'action_1'
    elif action == 'action_2':
        print 'action_2'
    else:
        old_onClickAction(self, typeID, entityID, action)
NotificationListView.onClickAction = new_onClickAction

Спасибо! Я нашел другой способ. А вы случайно не знаете как получить ID аккаунта в клиенте?

import BigWorld
import json
from urllib import urlopen
from gui import SystemMessages
from Account import Account

link = Account.onBecomePlayer

text = urlopen('https://api.worldoftanks.ru/wot/account/list/?application_id=demo&search=Aydomir').read()
obj = json.loads(text)

def _First(self):
        link(self)
        wn8 = obj['status']
        msg = '<font color="#cc9933"><b>'+wn8+'</b></font>'
        type = SystemMessages.SM_TYPE.Warning
        SystemMessages.pushMessage(msg, type)
        Account.onBecomePlayer = link

Account.onBecomePlayer = _First
Edited by Aydomir

Share this post


Link to post

Short link
Share on other sites

Спасибо! Я нашел другой способ. А вы случайно не знаете как получить ID аккаунта в клиенте?

from gui.shared import g_itemsCache
import BigWorld
from gui import SystemMessages
from Account import Account

from json import load
from urllib import urlopen

plId = g_itemsCache.items.getAccountDossier().getPlayerDBID()
if not plId:
   plId = BigWorld.player().id

obj = load(urlopen('http://api.worldoftanks.ru/wot/account/info/?application_id=demo&account_id={0}'.format(plId)))

link = Account.onBecomePlayer
def _First(self):
   link(self)
   wn8 = obj['status']
   msg = '<font color="#cc9933"><b>'+wn8+'</b></font>'
   type_ = SystemMessages.SM_TYPE.Warning
   SystemMessages.pushMessage(msg, type_)
   Account.onBecomePlayer = link

Account.onBecomePlayer = _First
Edited by ShadowHunterRUS

Share this post


Link to post

Short link
Share on other sites
from gui.shared import g_itemsCache
import BigWorld
from json import load
from urllib import urlopen
from gui import SystemMessages
from Account import Account

link = Account.onBecomePlayer


plId = g_itemsCache.items.getAccountDossier().getPlayerDBID()

obj = load(urlopen('http://api.worldoftanks.ru/wot/account/info/?application_id=demo&account_id={0}'.format(plId)))

def _First(self):
        link(self)
        wn8 = obj['status']
        msg = '<font color="#cc9933"><b>'+wn8+'</b></font>'
        type_ = SystemMessages.SM_TYPE.Warning
        SystemMessages.pushMessage(msg, type_)
        Account.onBecomePlayer = link

Account.onBecomePlayer = _First

Интересно, а я нашел такой способ 

text = urlopen('https://api.worldoftanks.ru/wot/account/list/?application_id=8dda4d6a0ab9e1299d3a4318d5a277f6&search='+BigWorld.player().name).read()

Share this post


Link to post

Short link
Share on other sites

Интересно, а я нашел такой способ

Для начала поместите ваши цитаты под спойлер.

Во вторых Вы делаете лишний запрос для того, чтобы узнать account_id, хотя можно сразу грузить стату по playerId

Edited by ShadowHunterRUS

Share this post


Link to post

Short link
Share on other sites

Для начала поместите ваши цитаты под спойлер.
Во вторых Вы делаете лишний запрос для того, чтобы узнать account_id, хотя можно сразу грузить стату по playerId

 

Да, это я понимаю. Я уже использую Ваш пример.

Share this post


Link to post

Short link
Share on other sites

в ангаре:

BigWorld.player().databaseID

в бою:

player = BigWorld.player()
player.arena.vehicles[player.playerVehicleID]['accountDBID']

Share this post


Link to post

Short link
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...