FIX sessionNotFound at initiation - python

I'm trying to build my fix application with quickfix, but when starting it, it first sends a logout message before logging in, and raises Session not Found.
class Application(quickfix.Application):
def __init__(self, session, logger):
super(Application, self).__init__()
self.session = session
self.logger = logger
def onCreate(self, sessionID):
self.logger.info("Created session {}.".format(sessionID))
return
def onLogon(self, sessionID):
self.logger.info("Logon session {}.".format(sessionID))
return
def onLogout(self, sessionID):
self.logger.info("Logout session {}.".format(sessionID))
return
def toAdmin(self, message, sessionID):
msgType = quickfix.MsgType()
message.getHeader().getField(msgType)
if msgType.getValue() == quickfix.MsgType_Logon:
self.logger.info('LOGON SessionID {}'.format(sessionID))
elif msgType.getValue() == quickfix.MsgType_Logout:
self.logger.info('LOGOUT SessionID {}'.format(sessionID))
self.logger.info('to Admin session {} send {}'.format(sessionID, self.messageToString(message)))
self.session.sendToTarget(message)
return
def toApp(self, message, sessionID):
self.logger.info('to App: {}'.format(message))
self.session.sendToTarget(message)
return
def fromApp(self, message, sessionID):
self.logger.info('from App: {}'.format(message))
return
logger = create_logger(config)
settings = quickfix.SessionSettings(client_config)
application = Application(quickfix.Session, logger)
storeFactory = quickfix.FileStoreFactory(settings)
logFactory = quickfix.ScreenLogFactory(settings)
initiator = quickfix.SocketInitiator(application, storeFactory, settings, logFactory)
initiator.start()
I get the following:
LOGOUT SessionID FIX44:Client->Server
to Admin session FIX44:Client->Server send 8=FIX.4.4|9=62|35=5|34=26|49=Client|52=20200608-12:26:03|56=Server|10=168
File "FIx.py", line 42, in toAdmin self.session.sendToTarget(message)
SessionNotFound: Session Not Found
Any idea why it raises the message please?
Thank you folks!

The from/toApp or from/toAdmin methods are callbacks and you should NOT send the passed message by yourself via Session.sendToTarget.
Instead the message will be sent by quickfix when the callback returns.

Related

slixmpp Add_event_hanlder ('Message') not working

I am creating a client with python and "slixmpp" library to connect using xmpp. I have achieved to send a message to a user, but I am not able to recive a message in the program. I am testing with another client (Gajim) to run some test but in that client the message are being recived.
My client has this plugins and this event listeners
class Client(slixmpp.ClientXMPP):
"""
A client class to manage conections an functionalities
Atributes:
jid: string with the JID of the client.
password: string
is_remove: boolean to indicate if need to delete the account
"""
def __init__(self, jid, password, status, status_message):
super().__init__(jid, password)
self.name = jid.split('#')[0]
self.status = status
self.status_message = status_message
self.actual_chat = None
# # plugins
self.register_plugin('xep_0030') # Service Discovery
self.register_plugin('xep_0199') # Ping
self.register_plugin('xep_0045') # MUC
self.register_plugin('xep_0085') # Notifications
self.register_plugin('xep_0004') # Data Forms
self.register_plugin('xep_0060') # PubSub
# events
self.add_event_handler('session_start', self.start)
self.add_event_handler('disco_items', self.print_rooms)
self.add_event_handler('groupchat_message', self.chatroom_message)
self.add_event_handler('message', self.chat_recived)
And this is the function chat_recived
async def chat_recived(self, message):
await aprint('aa')
await aprint('New message', message)
if message['type'] == 'chat':
user = str(message['from']).split('#')[0]
if user == self.actual_chat:
print(f'{message["from"]}: {message["body"]}')
else:
print(f'You have a new message from {message["from"]}')
Does anyone knows why the listener is not reciving the message? This are not even been display in the console when debuger mode is on.

I am getting key error when trying to access flask session data from another handler function

I am using dialogflow fulfillment flask package to build a simple chatbot. When I try to access the session variable in the def goalName(agent) handler that I set previously in the get_Name_ID(agent) handler, I get a key error message from the Heroku logs.
here is the webhook I am using:
#app.route('/webhook', methods=['POST', 'GET'])
def webhook() -> Dict:
"""Handle webhook requests from Dialogflow."""
# Get WebhookRequest object
request_ = request.get_json(force=True)
# Log request headers and body
logger.info(f'Request headers: {dict(request.headers)}')
logger.info(f'Request body: {request_}')
# Handle request
agent = WebhookClient(request_)
action = request_.get('queryResult').get('action')
if action == "get.secret.key":
agent.handle_request(get_Name_ID)
if action == "goal.setting.name":
agent.handle_request(goalName)
here is the first handler function
def get_Name_ID(agent):
task = TASK.query.filter_by(status="active").first()
if not USER.query.filter_by(passcode = agent.parameters["id"]).first():
user = USER(agent.parameters["id"], agent.parameters["name"])
db.session.add(user)
db.session.commit()
# store variables into session for later usage
key = id_generator()
user_session = SESSION(task.id, key)
db.session.add(user_session)
db.session.flush()
# store values to session
session['s_id'] = user_session.id
session['u_id'] = agent.parameters["id"]
session['user_name'] = agent.parameters["name"]
db.session.commit()
here is the second handler function:
def goalName(agent):
task = TASK.query.filter_by(status="active").first()
# print(type(redish.get('u_id')))
# print(redish.get('u_id'))
# get values from session
uid = session['u_id']
sid = session['s_id']
goal = GOAL(uid, task.id, sid, agent.parameters["goalName"], "", "", "", "", "")
db.session.add(goal)
db.session.flush()
session['goal_id'] = goal.id
db.session.commit()
I have setup the flask-session in the following manner:
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY') or \
'e5ac358c-f0bf-11e5-9e39-d3b532c10a28'
app.config['SESSION_TYPE'] = 'sqlalchemy'
db = SQLAlchemy(app)
app.config['SESSION_SQLALCHEMY'] = db
sess = Session(app)
I have tried the following methods:
removing the flask-session package and using built-in flask session but with no success.
I have set up simple routes to test the session and it was working fine. But it fails to work within the handler functions.
I am getting the key error when accessing session data from the second handler:
_ 2021-08-05T10:47:48.928371+00:00 app[web.1]: return super().getitem(key) 2021-08-05T10:47:48.928372+00:00 app[web.1]: KeyError: 'u_id
I am not sure what is going on? Any help would be much appreciated!
You can use redis server for session. It Will be solved your issue

LocustIO test result for post calls

How does post call work with LOcustIO? I was suspecting Locust not doing what it is suppose to do because it was returning success for all load testing I was running so I decided to post, write to the DB via a web application using LocustIO, to my surprise nothing was written to the db. Though I know some have successfully done this, so I want to know how to write to the Db using LocustIO as part of my load testing.
This is the code used:
from locust import HttpLocust, TaskSet, task
import logging, sys
from credentials import *
class LoginWithUniqueUsersSteps(TaskSet):
institutionCode = "NOT_FOUND"
username = "NOT_FOUND"
password = "NOT_FOUND"
def on_start(self):
if len(USER_CREDENTIALS) > 0:
self.institutionCode, self.username, self.password = USER_CREDENTIALS.pop()
#task
def login(self):
self.client.post("/dejavuweb/", {
'institutionCode': self.institutionCode, 'email': self.username, 'password': self.password
})
logging.info('Login with %s institutionCode %s username and %s password', self.institutionCode, self.username, self.password)
#task
def createTerminal(self):
response = self.client.request(method="POST", url="/dejavuweb/Home#Function/7", data= {"TerminalName": "RealterminalName"})
print("Create; Response status code:", response.status_code)
print("Create; Response content:", response.content)
class LoginWithUniqueUsersTest(HttpLocust):
task_set = LoginWithUniqueUsersSteps
host = "http://dev.trublend.cloud"
sock = None
def __init__(self):
super(LoginWithUniqueUsersTest, self).__init__()
Mind you, I copied, edited the code snippet above to achieve what I want.
Screenshot of LocustIO result:

logging file does not exist when running in celery

first, I'm sorry about my low level english
I create a website for study
I create send SMS feature using django + redis + celery
tasks/send_buy_sms.py
from celery import Task
from items.utils import SendSMS
class SendBuyMessageTask(Task):
def run(self, buyer_nickname, buyer_phone, saler_phone, selected_bookname):
sms = SendSMS()
sms.send_sms(buyer_nickname, buyer_phone, saler_phone, selected_bookname)
items/utils.py
import os
import requests
import json
class SendSMS():
def send_sms(self, buyer_nickname, buyer_phone, saler_phone, selected_bookname):
appid = [...]
apikey = [...]
sender = '...'
receivers = [saler_phone, ]
content = '...'
url = os.environ.get("URL")
params = {
'sender': sender,
'receivers': receivers,
'content': content,
}
headers = {...}
r = '...'
return params
when I send sms using my code it has no problem
[2017-09-12 17:20:43,532: WARNING/Worker-6] Task success
and I want make log file and insert log "success send SMS" when user click "send sms button"
wef/wef/decorators.py
from django.utils import timezone
import logging
def log_decorator(func):
logging.basicConfig(filename='../../sendsms.log', level=logging.INFO)
def wrap_func(self, *args, **kwargs):
time_stamp = timezone.localtime(timezone.now()).strftime('%Y-%m-%d %H:%M')
logging.info('[{}] success send SMS'.format(time_stamp))
print(logging)
return func(self, *args, **kwargs)
return wrap_func
but when I click 'send sms' button task is Ok , but log file doesn't created...
So I want to know 'what is the problem?'
I change my code create logfile -> print log
wef/wef/decorators.py
from django.utils import timezone
def log_decorator(func):
def wrap_func(self, *args, **kwargs):
time_stamp = timezone.localtime(timezone.now()).strftime('%Y-%m-%d %H:%M')
## print log
print('[{}] succes send sms'.format(timestamp))
## print log
return func(self, *args, **kwargs)
return wrap_func
when I click 'send sms button' the log print in celery
I'm so confused because print() is working but create log file doesn't working...
I think my code(create logging file) is no problem because when I practice create log file without django,celery,redis, log file was created successfully
same code, same feature but not working in django and celery
please give me some advise thank you
I guess you have to add logger like -
# import the logging library
import logging
# Get an instance of a logger
logger = logging.getLogger(__name__)
def my_view(request, arg1, arg):
...
if bad_mojo:
# Log an error message
logger.error('Something went wrong!')
Here I am assuming that you have configured your loggers, handlers, filters and formatters
For more information visit URL

How to send a message to a Channel from a Command

How do you send a message to a Django Consumer from a custom manage.py command
from django.core.management.base import BaseCommand, CommandError
from channels import Channel
class Command(BaseCommand):
help = 'Sends a message to a Django channel from the thing'
def add_arguments(self, parser):
parser.add_argument('json_object', nargs='+', type=str)
def handle(self, *args, **options):
self.stdout.write("TEST !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
print Channel("test").channel_layer
Channel("test").send({'op':options['json_object'][0]})
This is my consumer
class MyConsumer(WebsocketConsumer):
#classmethod
def channel_names(self):
return {"test"}
def connection_groups(self):
return ["test"]
def dispatch(self, message, **kwargs):
return self.get_handler(message, **kwargs)(message, **kwargs)
def get_handler(self, message, **kwargs):
channel_routing = [
consumers.MyConsumer.as_route(path=r"^/test/"),
route("test.receive", consumers.chat_join),
] for _filter, value in kwargs.items():
filter_mapping = getattr(self, _filter + '_mapping', None)
if not filter_mapping:
continue
consumer = getattr(self, filter_mapping.get(value), None)
if consumer:
return consumer
raise ValueError('Message')
def connect(self,message):
self.message.reply_channel.send({"accept": True})
def receive(self,text=None, bytes= None):
print text
def disconnect(self,message):
pass
When I try to run the command however, I get this message
2017-03-08 03:45:33,839 - ERROR - worker - Could not find match for message on test! Check your routing.
In case it is pertinent, here is my routing
channel_routing = [
consumers.MyConsumer.as_route(path=r"^/test/"),
]
In short, add the path to the content you'd like to send:
Channel("test").send({
'op':options['json_object'][0],
'path': '/test/',
})
And that's it!
I ran into the same problem and I found out that it is because I am using the as_route method of generic consumer to generate route_class, which always has path as its filter.
If we use route instead we do not necessarily provide the path argument and that's the reason why the code at the doc (https://channels.readthedocs.io/en/stable/getting-started.html#models) works

Categories