Inhalte aus Drupal sollen mittels REST zu Wordpress übetragen werden. Ein kleines Python Script erledigt den Abgleich.

REST API in Drupal 7 mittels Services

Drupal 8 hat die REST API im Kern, bei Drupal 7 lässt sich das mit dem services Modul nachinstallieren.

Aktion bei Seitenänderung ausführen

REST API in Wordpress

Wordpress sagen das custom_meta_boxes vie REST geändert werden dürfen

add_action( 'rest_api_init', 'register_my_metaboxes_to_rest' );

function register_event_metaboxes_to_rest() {
        $fields = [
                //'post_content',
                'event_date_start',
                'event_doors',
                'event_date_start_ts',
                'event_is_multiday',
                'event_date_end',
                'event_room',
                'event_resident',
                'event_ticket_url',
                'external_node_id',
                'external_ctime'
        ];
        foreach ( $fields as $field ) {
                register_field_to_rest( $field );
        }
}

function register_field_to_rest( $field ) {
        register_rest_field( 'event', $field, array(
                'get_callback'    => function ( $data, $field ) {
                        return get_post_meta( $data['id'], $field, true );
                },
                'update_callback' => function ( $value, $post, $field ) {
                        // TODO: sanitize and validate this field better
                        $value = sanitize_text_field( $value );
                        update_post_meta( $post->ID, $field, $value );
                }
        ) );
}


Webclient

Python REST Client

Python REST Beispiele

Vorbereitung für oauth1

def oauth1_threeleggedflow():
    """ for three legged oauth follow the docs at:
    http://requests-oauthlib.readthedocs.io/en/latest/oauth1_workflow.html
    """
    oauthkey = config['oauth']['key']
    oauthpass = config['oauth']['pw']
    callback = config['oauth']['callback']
    oauth = OAuth1Session(client_key=oauthkey,
                          client_secret=oauthpass, callback_uri=callback)
    logging.debug("open OAuth session")

    """ 1.) request token runterladen
    """
    fetch_response = oauth.fetch_request_token(config['oauth']['request'],
                                               oauthkey)
    resource_owner_key = fetch_response.get('oauth_token')
    logging.debug(resource_owner_key)
    resource_owner_secret = fetch_response.get('oauth_token_secret')
    logging.debug(resource_owner_secret)

    """ 2.) durch user authorisieren lassen
    und damit den verifier link zum access token bekommen
    """
    authorization_url = oauth.authorization_url(config['oauth']['authorize'])
    print('Please login to wordpress go there and authorize: '
          + authorization_url)
    redirect_response = input('Afterwards paste the full redirect URL here: ')
    oauth_response = oauth.parse_authorization_response(redirect_response)
    logging.debug(oauth_response)
    oauth_verifier = oauth_response.get('oauth_verifier')
    logging.warning(oauth_verifier)

    """ 3.) access token holen
    """
    oauth = OAuth1Session(oauthkey,
                          client_secret=oauthpass,
                          resource_owner_key=resource_owner_key,
                          resource_owner_secret=resource_owner_secret,
                          verifier=oauth_verifier)
    oauth_tokens = oauth.fetch_access_token(config['oauth']['access'])
    # gut merken...
    oauth_token = oauth_tokens.get('oauth_token')
    logging.info(oauth_token)
    # gut merken...
    oauth_token_secret = oauth_tokens.get('oauth_token_secret')
    logging.info(oauth_token_secret)

Wordpress Post erstellen

def post_content(payload):
    """ post the given payload as wp event
    """
    domain = config['website']['domain']
    postpath = config['website']['postpath']
    url = domain + postpath
    oauthkey = config['oauth']['key']
    oauthpass = config['oauth']['pw']
    oauth_token = config['oauth']['token']
    oauth_token_secret = config['oauth']['secret']
    head = {'Content-Type': 'application/json',
            'user-agent': 'RESTeRampe'}
    pwhwp = OAuth1Session(oauthkey,
                          client_secret=oauthpass,
                          resource_owner_key=oauth_token,
                          resource_owner_secret=oauth_token_secret)
    r = pwhwp.post(url, json=payload, headers=head)
    logging.info("HTTP status: " + str(r.status_code) + "\n")
    logging.info("HTTP json: " + str(r.json()))

Bild zu Wordpress hochladen

def post_image(imagepath):
    """ upload image to wordpress site
    """
    domain = config['website']['domain']
    imagepostpath = config['website']['imagepostpath']
    url = domain + imagepostpath
    oauthkey = config['oauth']['key']
    oauthpass = config['oauth']['pw']
    oauth_token = config['oauth']['token']
    oauth_token_secret = config['oauth']['secret']
    path, filename = os.path.split(imagepath)
    head = {'user-agent': 'RESTeRampe',
            'Cache-Control': 'no-cache',
            'Content-Type': 'image/jpeg',
            'Content-Disposition': 'attachment; filename=' + filename
            }
    payload = {'status': 'publish' # set the event as public in wordpress
            }
    pwhwp = OAuth1Session(oauthkey,
                          client_secret=oauthpass,
                          resource_owner_key=oauth_token,
                          resource_owner_secret=oauth_token_secret)
    with open(imagepath, "rb") as image:
        data = image.read()
    r = pwhwp.post(url, data=data, headers=head)
    logging.info("HTTP status: " + str(r.status_code) + "\n")
    logging.info("HTTP json: " + str(r.json()))
    image_id = r.json()['id'] # save id of new uploaded image
    logging.info("wp image id: %s", str(image_id))
    return image_id

DrupalWordpressREST (zuletzt geändert am 2017-07-28 11:43:55 durch anonym)


Creative Commons Lizenzvertrag
This page is licensed under a Creative Commons Attribution-ShareAlike 2.5 License.