JIRA do I have a way to get the list all ID of my transition steps? - jira

I want to synchronize between two systems. However, to update the transition status of the bug I have to send a JSON file with my arguments (new status) something like this:
{
"update": {
"comment": [
{
"add": {
"body": "Comment added when resolving issue"
}
}
]
},
"transition": {
"id": "5"
}
}
To set a new status I have to set it's id, How can I get the list of all the IDs and the description of each one.

You can get a list of the transitions possible for this issue by the current user, along with fields that are required and their types by url /rest/api/2/issue/{issueIdOrKey}/transitions (get request)

You can use the following python script to get the information you want.
#!/usr/bin/env python
from __future__ import print_function
import ConfigParser
import requests
import json
import base64
import sys
def print_error(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def get_issue(user,password,search_url):
user_auth = base64.b64encode(user+':'+password)
headers = {'Authorization': 'Basic ' + user_auth}
return requests.get(search_url, headers=headers)
def main():
if len(sys.argv) < 2:
usage_message = 'Usage: ' + sys.argv[0] + ' issue_number'
print_error(usage_message)
sys.exit(1)
config = ConfigParser.RawConfigParser()
config.read('config.properties')
jira_user = config.get('Global', 'jira_user')
jira_pass = config.get('Global', 'jira_pass')
jira_base_url = config.get('Global', 'jira_base_url')
issue_url = config.get('Global', 'issue_url')
issue = sys.argv[1]
issue_search_url = jira_base_url + issue_url + issue + '/transitions'
response = get_issue(jira_user,jira_pass,issue_search_url)
if response.status_code == 404:
print_error(issue + ' NOT FOUND!')
sys.exit(1)
data = response.json()
for transition in data['transitions']:
print("%s %s" % (transition['id'], transition['name']))
main()
You need to have a configuration file (config.properties) in the same directory as the script with the following content:
[Global]
jira_user=username
jira_pass=pass
jira_base_url=http://your_jira_url.com
issue_url=/rest/api/2/issue/
Then you call the script like this:
./get_transitions.py your_ticket_number

Related

12200 - Schema validation warning twilio

Hi team i need to fix the 12200 - Schema validation warning twilio.
everything is working but i dont receive the whatsapp respond back .
enter image description here
here is the app.py code:
from helper.openai_api import text_complition
from helper.twilio_api import send_message
from twilio.twiml.messaging_response import MessagingResponse
from flask import Flask, request
from dotenv import load_dotenv
load_dotenv()
app = Flask(__name__)
#app.route('/')
def home():
return 'All is well...'
#app.route('/twilio/receiveMessage', methods=['POST'])
def receiveMessage():
try:
message = request.form['Body']
sender_id = request.form['From']
# Placeholder code
result = {}
result['status'] = 1
result['response'] = "Hi, I'm CODAI, I have received your message."
send_message(sender_id, result['response'])
except:
pass
return 'OK', 200
here is the openai.py code:
import os
import openai
from dotenv import load_dotenv
from twilio.twiml.messaging_response import MessagingResponse
load_dotenv()
openai.api_key = os.getenv('OPENAI_API_KEY')
def text_complition(prompt: str) -> dict:
'''
Call Openai API for text completion
Parameters:
- prompt: user query (str)
Returns:
- dict
'''
try:
response = openai.Completion.create(
model='text-davinci-003',
prompt=f'Human: {prompt}\nAI: ',
temperature=0.9,
max_tokens=150,
top_p=1,
frequency_penalty=0,
presence_penalty=0.6,
stop=['Human:', 'AI:']
)
return {
'status': 1,
'response': response['choices'][0]['text']
}
except:
return {
'status': 0,
'response': ''
}
here is the twilio.py code:
import os
from twilio.twiml.messaging_response import MessagingResponse
from twilio.rest import Client
from dotenv import load_dotenv
load_dotenv()
account_sid = os.getenv('TWILIO_ACCOUNT_SID')
auth_token = os.getenv('TWILIO_AUTH_TOKEN')
client = Client(account_sid, auth_token)
def send_message(to: str, message: str) -> None:
'''
Send message through Twilio's WhatsApp API.
Parameters:
- to(str): recipient's phone number in the format of "whatsapp:+[country code][phone number]"
- message(str): text message to send
Returns:
- None
'''
_ = client.messages.create(
from_=os.getenv('FROM'),
body=message,
to="whatsapp:" + to
)
i need help to fix the error 12200 - Schema validation warning twilio

Batch update failed: update results in the schema exceeding the page break limit

I was trying to create an automatic form using the Forms API in python.
When I try to create more than 100 page breaks I came across the following error:
"HttpError 400 (...) returned "Batch update failed: update results in the schema exceeding the page break limit". Details: "Batch update failed: update results in the schema exceeding the page break limit".
The code I performed was the following:
from __future__ import print_function
from apiclient import discovery
from httplib2 import Http
from oauth2client import client, file, tools
import time
SCOPES = "https://www.googleapis.com/auth/forms.body"
DISCOVERY_DOC = "https://forms.googleapis.com/$discovery/rest?version=v1"
store = file.Storage('token.json')
creds = None
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('client_secrets.json', SCOPES)
creds = tools.run_flow(flow, store)
form_service = discovery.build('forms', 'v1', http=creds.authorize(
Http()), discoveryServiceUrl=DISCOVERY_DOC, static_discovery=False)
# Request body for creating a form
NEW_FORM = {
"info": {
"title": "TEST V0.0.1",
"documentTitle": "TEST V0.0.1",
}
}
BREAK_ITEM = {
"requests": [{
"createItem": {
"item":{
"pageBreakItem": {
},
},
"location": {
"index": 0
}
}
}]
}
# Creates the initial form
result = form_service.forms().create(body=NEW_FORM).execute()
for i in range(200):
question_setting = form_service.forms().batchUpdate(formId=result["formId"],body=BREAK_ITEM).execute()
print(i)
time.sleep(1)
# Prints the result to show the question has been added
get_result = form_service.forms().get(formId=result["formId"]).execute()
print(get_result)
If I change the number of times the cycle repeats (to under 100 times), the code works fine.
How can I overcome this?

How to send result of function from Django Server to React Native App?

I am study React Native and Django Development and I create an app which recognize a text from image. I realized POST method from React Native to Django Server but I don't understand how to send the result of recognition back to React.
How I can resolve this problem?
Django Server:
views.py:
from .serializers import PostSerializer
from .models import Ocr
from rest_framework.views import APIView
from rest_framework.parsers import MultiPartParser, FormParser
from rest_framework.response import Response
from rest_framework import status
# Create your views here.
from django.http.response import JsonResponse
# Create your views here.
# import pytesseract to convert text in image to string
import pytesseract
# import summarize to summarize the ocred text
from .forms import ImageUpload
import os
# import Image from PIL to read image
from PIL import Image
from django.conf import settings
# Create your views here.
class PostView(APIView):
parser_classes = (MultiPartParser, FormParser)
def get(self, request, *args, **kwargs):
posts = Ocr.objects.all()
serializer = PostSerializer(posts, many=True)
print(serializer.data)
return Response(serializer.data)
def post(self, request, *args, **kwargs):
posts_serializer = PostSerializer(data=request.data)
if posts_serializer.is_valid():
text = ""
message = ""
posts_serializer.save()
try:
posts_serializer.save()
image = request.FILES['image']
image = image.name
path = settings.MEDIA_ROOT
pathz = path + "/images/" + image
text = pytesseract.image_to_string(Image.open(pathz), lang='rus+eng')
os.remove(pathz)
except Exception:
message = "check your filename and ensure it doesn't have any space or check if it has any text"
context = {
'text': text,
'message': message
}
print(context)
return Response(posts_serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(posts_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
React-Native:
CameraScreen.js:
const postToServer = (img) => {
const formData = new FormData();
formData.append('image', {
uri: img.uri,
type: 'image/jpeg',
name: 'test.jpg',
})
formData.append('title', 'title');
fetch('http://192.168.0.149:8000/api/textocr/', {
method: 'POST',
body: formData,
// If you add this, upload won't work
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
}
});
}

Django channels: messages are duplicated in a one channel

I'm going through official Django Channels tutorial and get stacked with the same problem as this guy:
Django Channels group send only sends the message to last channel
So, I have a bunch of standard files:
# asgi.py
import os
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application
import chat.routing
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
application = ProtocolTypeRouter({
"http": get_asgi_application(),
"websocket": AuthMiddlewareStack(
URLRouter(
chat.routing.websocket_urlpatterns
)
),
})
# routing.py
from django.urls import re_path
from . import consumers
websocket_urlpatterns = [
re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer.as_asgi()),
]
# consumers.py
import json
from channels.generic.websocket import AsyncWebsocketConsumer
class ChatConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.room_name = self.scope['url_route']['kwargs']['room_name']
self.room_group_name = 'chat_%s' % self.room_name
await self.channel_layer.group_add(
self.room_group_name,
self.channel_name
)
await self.accept()
async def disconnect(self, close_code):
await self.channel_layer.group_discard(
self.room_group_name,
self.channel_name
)
async def receive(self, text_data):
print('def receive from websocket')
text_data_json = json.loads(text_data)
message = text_data_json['message']
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'chat_message',
'message': message
}
)
async def chat_message(self, event):
message = event['message']
await self.send(text_data=json.dumps({
'message': message
}))
And a part of settings.py
ASGI_APPLICATION = 'mysite.asgi.application'
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
"hosts": [('127.0.0.1', 6379)],
},
},
}
This is a simple chat room. I open two tabs in the same browser, text "Hello" in the first one and get two "Hello" inside of the second tab with zero "Hello" in the first tab.
UPDATE!!!
I made some experiments and I think that consumers functions work correctly (I logged channel_name parameter during the messages sending and inside def receive() I can see exactly that channel_name, from which I sent a message, and at the same time inside def chat_message() I can see all channels). So, the problem should be in js?
<textarea id="chat-log" cols="100" rows="20"></textarea><br>
<input id="chat-message-input" type="text" size="100"><br>
<input id="chat-message-submit" type="button" value="Send">
{{ room_name|json_script:"room-name" }}
<script>
const roomName = JSON.parse(document.getElementById('room-name').textContent);
const chatSocket = new WebSocket(
'ws://'
+ window.location.host
+ '/ws/chat/'
+ roomName
+ '/'
);
chatSocket.onmessage = function(e) {
const data = JSON.parse(e.data);
document.querySelector('#chat-log').value += (data.message + '\n');
};
chatSocket.onclose = function(e) {
console.error('Chat socket closed unexpectedly');
};
document.querySelector('#chat-message-input').focus();
document.querySelector('#chat-message-input').onkeyup = function(e) {
if (e.keyCode === 13) { // enter, return
document.querySelector('#chat-message-submit').click();
}
};
document.querySelector('#chat-message-submit').onclick = function(e) {
const messageInputDom = document.querySelector('#chat-message-input');
const message = messageInputDom.value;
chatSocket.send(JSON.stringify({
'message': message
}));
messageInputDom.value = '';
};
</script>
The problem is solved. In my case it was with django environment. I used the common one, which I also use for other projects. Maybe the reason of issue was in conflict between some installs. I've created a new environment, installed django and channels and everything is working now.
I faced this issue too. I think this is a bug in channels=3.0.0
I upgraded to channels=3.0.4 and it is working now!

Messages in Django Channels sent outside consumer not being received

I'm trying to send messages to specific websocket instances, but neither channel_layer.send, nor using channel_layer.group_send with unique groups for each instance seems to be working, no errors are being raised, they just aren't received by the instances.
The function that sends the message is:
def listRequest(auth_user, city):
request_country = city["country_name"]
request_city = city["city"]
request_location = request_city +", "+request_country
concatenate_service_email = auth_user.service + "-" + auth_user.email
this_request = LoginRequest(service_and_email=concatenate_service_email, location=request_location)
this_request.generate_challenge()
this_request.set_expiry(timezone.now() + timezone.timedelta(minutes=5))
this_request.save()
channel_layer = get_channel_layer()
print(auth_user.current_socket)
async_to_sync(channel_layer.group_send)(
auth_user.current_socket,{
"type": "new.request",
"service_and_email" : concatenate_service_email
},
)
My current working consumers.py (receive and scanrequest don't have anything that's likely to be relevant to the issue):
from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer
from .helpers import verify_identity, unique_group
from django.utils import timezone
from .models import Authentication, LoginRequest
import json
import time
class AuthConsumer(WebsocketConsumer):
account_list =[]
def connect(self):
print("Connect attempted")
print(self.channel_name)
print(unique_group(self.channel_name))
async_to_sync(self.channel_layer.group_add)(unique_group(self.channel_name), self.channel_name)
self.accept()
def disconnect(self, close_code):
print("Disconnect attempted")
async_to_sync(self.channel_layer.group_discard)(unique_group(self.channel_name), self.channel_name)
for i in self.account_list:
serviceEmailSplit = i.split("-")
try:
auth_user = Authentication.objects.get(service=serviceEmailSplit[0],email=serviceEmailSplit[1])
auth_user.set_socket("NONE")
auth_user.save()
except:
print("Error user %s does not exist" %i)
pass
def receive(self, text_data):
print("Receiving data")
if text_data[0:7] == "APPROVE":
data_as_list = text_data.split(",")
serviceEmailSplit = data_as_list[1].split("-")
auth_user = Authentication.objects.get(service=serviceEmailSplit[0],email=serviceEmailSplit[1])
this_request = LoginRequest.objects.get(service_and_email=data_as_list[1],approved=False, expiry__gt=timezone.now())
if verify_identity(auth_user.public_key, data_as_list[2], this_request.challenge):
this_request.set_approved()
self.send("Request Approved!")
else:
self.send("ERROR: User verification failed")
else:
self.account_list = text_data.split(",")
self.account_list.pop(-1)
print(self.account_list)
for i in self.account_list:
serviceEmailSplit = i.split("-")
try:
auth_user = Authentication.objects.get(service=serviceEmailSplit[0],email=serviceEmailSplit[1])
auth_user.set_socket(unique_group(self.channel_name))
auth_user.save()
except:
self.send("Error user %s does not exist" %i)
self.scanRequest()
def scanRequest(self):
requestSet = LoginRequest.objects.filter(service_and_email__in = self.account_list, approved = False, request_expiry__gt = timezone.now())
if requestSet.count() > 0:
for request in requestSet:
self.send(request.service_and_email+","+request.location+","+str(request.challenge))
else:
self.send("NOREQUESTS")
def new_request(self,event):
print("NEW REQUEST!")
this_request = LoginRequest.objects.filter(service_and_email = event["service_and_email"]).latest('request_expiry')
self.send(this_request.service_and_email+","+this_request.location+","+str(this_request.challenge))
And my routing.py:
from django.urls import re_path
from . import consumers
from django.conf.urls import url
websocket_urlpatterns = [
url(r"^ws/$", consumers.AuthConsumer.as_asgi()),
]
"NEW REQUEST!" is never printed, having tried to call it both by sending a message directly, and neither does using groups like I have written above.
My redis server appears to be working from testing like the documentation for the channels tutorial suggests:
https://channels.readthedocs.io/en/stable/tutorial/part_2.html
I'm pretty stumped after attempts to fix it, and I've looked at the other posts on stackoverflow with the same/similar issues and I'm already following whatever solutions they have in my code.

Resources