(Probably I'm going to embarrass myself with the code below; I'm not professional and simply copy-paste code from tutorials, with lots of potential errors...)
I'm interested too in learning how the TLS works. This code here DOES NOT USE the new TLS thing (I need to study it, I don't have access to Renpytom's Patreon), but it uses old python2 libraries (urllib and urllib2) to connect to a HTTP (not HTTPS) url. I show this here only as a starting point, and ask for advice. What's wrong with my approach? How it should be done?
This is (simplified) the code I'm using in an app that informs a web server about the progress of the user. The user can also search for other users and follow them (set them as "friends"), and can see the progress other users have made (actually, there is a "champions chart", ordered by Xp points, not showed here). The user can also see what users are following him/her.
I'm showing here only some of the code:
1- connect.rpy, in Ren'Py, allows renpy to connect to the server.
Code: Select all
### CONNECT.rpy ###
default network = 1 ## this variable counts the times the urlopen has not been successful. 0==working
default webid = ''
default friends = []
default fans = []
default url = "http://mywebpage.com/mygame.php"
init python:
from urllib import urlencode
from urllib2 import urlopen
from json import load as json_load
def connect(action='inform'):
global network, webid, friends, fans
if webid == '':
action = 'create'
## Preparation of data
data_dict = {}
data_dict['action'] = action
if action == 'create':
data_dict['username'] = username
data_dict['pwh'] = pwh ## password-hashed
data_dict['webid'] = webid ## user's id given by the server
data_dict['version'] = config.version
## user's game progress:
data_dict['xp'] = xp
data_dict['mascot'] = mascot
data = urlencode(data_dict)
try:
response = urlopen(url, data=data, timeout=10)
except:
network += 1
return False
raw_result = json_load(response)
response.close()
friends = []
fans = []
if "CREATED" in raw_result:
webid = str(raw_result["CREATED"])
if "FRIENDS" in raw_result:
for element in raw_result["FRIENDS"]:
friends.append(element)
if "FANS" in raw_result:
for element in raw_result["FANS"]:
fans.append(element)
network = 0
return True
Code: Select all
<?php
// Version: 04/01/2018
// RETRIEVE THE VARIABLES:
$webid = htmlspecialchars($_REQUEST['webid']);
$webid = intval($webid);
$username = htmlspecialchars($_REQUEST['username']);
$pwh = htmlspecialchars($_REQUEST['pwh']);
$xp = htmlspecialchars($_REQUEST['xp']);
$mascot = htmlspecialchars($_REQUEST['mascot']);
$version = htmlspecialchars($_REQUEST['version']);
// LINK WITH THE DATABASE:
$link = mysqli_connect("MySQL hostname", "MySQL username", "MySQL password", "MYSQL databasename");
// To show special characters:
$tildes = $link->query("SET NAMES 'utf8'");
// Arrays for the json output:
$a = array();
$friends = array();
$fans = array();
// Creates a new user:
if ($action == 'create') {
// CREATE:
$result = mysqli_query($link, "INSERT INTO mygame_users (username, pwh, xp, mascot, version)
VALUES ('$username', '$pwh', '$xp', '$mascot', '$version')");
$a["CREATED"] = mysqli_insert_id($link);
$to = "some_email@mail.com";
$subject = "MY GAME: New User";
$message = "New User in my game: ".$username;
mail($to, $subject, $message);
// Updates user info AND gets all friends and 100 fans:
} elseif ($action == 'inform') {
// UPDATE INFO IN ROW...
$result = mysqli_query($link, "UPDATE mygame_users
SET xp = '$xp', mascot = '$mascot', version = '$version', updated=CURRENT_TIMESTAMP
WHERE webid = '$webid' AND pwh = '$pwh'");
// ...AND, IF SOME ROWS HAVE BEEN AFFECTED,...
if (mysqli_affected_rows($link) > 0) {
// ...GET THE FRIENDS...
$result = mysqli_query($link, "SELECT webid, username, xp, mascot, id
FROM mygame_users u
INNER JOIN mygame_friends f ON u.webid = f.friendid
WHERE f.userid = '$webid'");
while ($row = mysqli_fetch_assoc($result)) {
$friends[] = $row;
}
$a["FRIENDS"] = $friends;
// ...AND GET THE FANS... (maximum 100)
$result = mysqli_query($link, "SELECT webid, username, xp, mascot, id
FROM mygame_users u
INNER JOIN mygame_friends f ON u.webid = f.userid
WHERE f.friendid = '$webid' ORDER BY last_done DESC, streak DESC LIMIT 100");
while ($row = mysqli_fetch_assoc($result)) {
$fans[] = $row;
}
$a["FANS"] = $fans;
}
}
// HERE THERE IS MORE CODE TO SEARCH USERS, ADD THEM AS FRIENDS,
// DELETE FRIENDSHIP AND REPORT IN-GAME ERRORS.
// CLEANING UP:
mysqli_free_result($result);
mysqli_close($link);
// JSON OUTPUT:
echo json_encode($a, JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
2- Then you need
mygame.php, a PHP file in the server that dialogues with the database. With special attention to avoid SQL injection attacks.
- Takes the variables that the python code has passed (action, pwh, webid, version, xp, mascot).
- Makes changes in the database with the new info.
- Creates an output (I use json_encode), that will be read by Ren'Py.